index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/aws-sdk-java-v2/core/auth-crt/src/test/java/software/amazon/awssdk/authcrt/signer
Create_ds/aws-sdk-java-v2/core/auth-crt/src/test/java/software/amazon/awssdk/authcrt/signer/internal/CrtHttpRequestConverterTest.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.authcrt.signer.internal; import static org.assertj.core.api.Assertions.assertThat; import java.io.ByteArrayInputStream; import java.net.URI; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.crt.http.HttpHeader; import software.amazon.awssdk.crt.http.HttpRequest; import software.amazon.awssdk.crt.http.HttpRequestBodyStream; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.utils.BinaryUtils; public class CrtHttpRequestConverterTest { CrtHttpRequestConverter converter; @BeforeEach public void setup() { converter = new CrtHttpRequestConverter(); } @Test public void request_withHeaders_isConvertedToCrtFormat() { String data = "data"; SdkHttpFullRequest request = SdkHttpFullRequest.builder() .method(SdkHttpMethod.POST) .contentStreamProvider(() -> new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8))) .putHeader("x-amz-archive-description", "test test") .putHeader("Host", "demo.us-east-1.amazonaws.com") .encodedPath("/") .uri(URI.create("https://demo.us-east-1.amazonaws.com")) .build(); HttpRequest crtHttpRequest = converter.requestToCrt(request); assertThat(crtHttpRequest.getMethod()).isEqualTo("POST"); assertThat(crtHttpRequest.getEncodedPath()).isEqualTo("/"); List<HttpHeader> headers = crtHttpRequest.getHeaders(); HttpHeader[] headersAsArray = crtHttpRequest.getHeadersAsArray(); assertThat(headers.size()).isEqualTo(2); assertThat(headersAsArray.length).isEqualTo(2); assertThat(headers.get(0).getName()).isEqualTo("Host"); assertThat(headers.get(0).getValue()).isEqualTo("demo.us-east-1.amazonaws.com"); assertThat(headersAsArray[1].getName()).isEqualTo("x-amz-archive-description"); assertThat(headersAsArray[1].getValue()).isEqualTo("test test"); assertStream(data, crtHttpRequest.getBodyStream()); assertHttpRequestSame(request, crtHttpRequest); } @Test public void request_withQueryParams_isConvertedToCrtFormat() { SdkHttpFullRequest request = SdkHttpFullRequest.builder() .method(SdkHttpMethod.GET) .putRawQueryParameter("param1", "value1") .putRawQueryParameter("param2", Arrays.asList("value2-1", "value2-2")) .putHeader("Host", "demo.us-east-1.amazonaws.com") .encodedPath("/path") .uri(URI.create("https://demo.us-east-1.amazonaws.com")) .build(); HttpRequest crtHttpRequest = converter.requestToCrt(request); assertThat(crtHttpRequest.getMethod()).isEqualTo("GET"); assertThat(crtHttpRequest.getEncodedPath()).isEqualTo("/path?param1=value1&param2=value2-1&param2=value2-2"); assertHttpRequestSame(request, crtHttpRequest); } @Test public void request_withEmptyPath_isConvertedToCrtFormat() { SdkHttpFullRequest request = SdkHttpFullRequest.builder() .method(SdkHttpMethod.GET) .putHeader("Host", "demo.us-east-1.amazonaws.com") .encodedPath("") .uri(URI.create("https://demo.us-east-1.amazonaws.com")) .build(); HttpRequest crtHttpRequest = converter.requestToCrt(request); assertThat(crtHttpRequest.getEncodedPath()).isEqualTo("/"); assertHttpRequestSame(request, crtHttpRequest); } @Test public void request_byteArray_isConvertedToCrtStream() { byte[] data = new byte[144]; Arrays.fill(data, (byte) 0x2A); HttpRequestBodyStream crtStream = converter.toCrtStream(data); ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16*1024]); crtStream.sendRequestBody(byteBuffer); byteBuffer.flip(); String result = new String(BinaryUtils.copyBytesFrom(byteBuffer), StandardCharsets.UTF_8); assertThat(result.length()).isEqualTo(144); assertThat(result).containsPattern("^\\*+$"); } private void assertHttpRequestSame(SdkHttpFullRequest originalRequest, HttpRequest crtRequest) { SdkHttpFullRequest sdkRequest = converter.crtRequestToHttp(originalRequest, crtRequest); assertThat(sdkRequest.method()).isEqualTo(originalRequest.method()); assertThat(sdkRequest.protocol()).isEqualTo(originalRequest.protocol()); assertThat(sdkRequest.host()).isEqualTo(originalRequest.host()); assertThat(sdkRequest.encodedPath()).isEqualTo(originalRequest.encodedPath()); assertThat(sdkRequest.headers()).isEqualTo(originalRequest.headers()); assertThat(sdkRequest.rawQueryParameters()).isEqualTo(originalRequest.rawQueryParameters()); } private void assertStream(String expectedData, HttpRequestBodyStream crtStream) { ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16*1024]); crtStream.sendRequestBody(byteBuffer); byteBuffer.flip(); String result = new String(BinaryUtils.copyBytesFrom(byteBuffer), StandardCharsets.UTF_8); assertThat(result.length()).isEqualTo(expectedData.length()); assertThat(result).isEqualTo(expectedData); } }
1,800
0
Create_ds/aws-sdk-java-v2/core/auth-crt/src/test/java/software/amazon/awssdk/authcrt/signer
Create_ds/aws-sdk-java-v2/core/auth-crt/src/test/java/software/amazon/awssdk/authcrt/signer/internal/ChunkedEncodingFunctionalTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.authcrt.signer.internal; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import static software.amazon.awssdk.authcrt.signer.internal.SigningUtils.SIGNING_CLOCK; import static software.amazon.awssdk.authcrt.signer.internal.SigningUtils.buildCredentials; import static software.amazon.awssdk.authcrt.signer.internal.SigningUtils.getSigningClock; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.net.URI; import java.nio.charset.StandardCharsets; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.Clock; import java.time.ZoneId; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.TimeZone; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.io.IOUtils; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute; import software.amazon.awssdk.core.checksums.Algorithm; import software.amazon.awssdk.core.checksums.SdkChecksum; import software.amazon.awssdk.core.internal.chunked.AwsChunkedEncodingConfig; import software.amazon.awssdk.auth.signer.internal.chunkedencoding.AwsSignedChunkedEncodingInputStream; import software.amazon.awssdk.authcrt.signer.internal.chunkedencoding.AwsS3V4aChunkSigner; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.crt.auth.signing.AwsSigningConfig; import software.amazon.awssdk.crt.auth.signing.AwsSigningResult; import software.amazon.awssdk.crt.auth.signing.AwsSigningUtils; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.regions.Region; /** * Functional tests for the S3 specific Sigv4a signer. These tests call the CRT native signer code. Because * Sigv4 Asymmetric does not yield deterministic results, the signatures can only be verified by using * a pre-calculated test case and calling a verification method with information from that test case. */ @RunWith(MockitoJUnitRunner.class) public class ChunkedEncodingFunctionalTest { private static final String CHUNKED_SIGV4A_CANONICAL_REQUEST = "PUT\n" + "/examplebucket/chunkObject.txt\n" + "\n" + "content-encoding:aws-chunked\n" + "content-length:66824\n" + "host:s3.amazonaws.com\n" + "x-amz-content-sha256:STREAMING-AWS4-ECDSA-P256-SHA256-PAYLOAD\n" + "x-amz-date:20130524T000000Z\n" + "x-amz-decoded-content-length:66560\n" + "x-amz-region-set:us-east-1\n" + "x-amz-storage-class:REDUCED_REDUNDANCY\n" + "\n" + "content-encoding;content-length;host;x-amz-content-sha256;x-amz-date;x-amz-decoded-content-length;x-amz-region-set;x-amz-storage-class\n" + "STREAMING-AWS4-ECDSA-P256-SHA256-PAYLOAD"; private static final String CHUNKED_TRAILER_SIGV4A_CANONICAL_REQUEST = "PUT\n" + "/examplebucket/chunkObject.txt\n" + "\n" + "content-encoding:aws-chunked\n" + "content-length:66824\n" + "host:s3.amazonaws.com\n" + "x-amz-content-sha256:STREAMING-AWS4-ECDSA-P256-SHA256-PAYLOAD-TRAILER\n" + "x-amz-date:20130524T000000Z\n" + "x-amz-decoded-content-length:66560\n" + "x-amz-region-set:us-east-1\n" + "x-amz-storage-class:REDUCED_REDUNDANCY\n" + "x-amz-trailer:first,second,third\n" + "\n" + "content-encoding;content-length;host;x-amz-content-sha256;x-amz-date;x-amz-decoded-content-length;x-amz-region-set;x-amz-storage-class;x-amz-trailer\n" + "STREAMING-AWS4-ECDSA-P256-SHA256-PAYLOAD-TRAILER"; private static final String CHUNKED_ACCESS_KEY_ID = "AKIAIOSFODNN7EXAMPLE"; private static final String CHUNKED_SECRET_ACCESS_KEY = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"; private static final String CHUNKED_SIGV4A_TEST_ECC_PUB_X = "18b7d04643359f6ec270dcbab8dce6d169d66ddc9778c75cfb08dfdb701637ab"; private static final String CHUNKED_SIGV4A_TEST_ECC_PUB_Y = "fa36b35e4fe67e3112261d2e17a956ef85b06e44712d2850bcd3c2161e9993f2"; private static final String CHUNKED_TEST_REGION = "us-east-1"; private static final String CHUNKED_TEST_SERVICE = "s3"; private static final String CHUNKED_TEST_SIGNING_TIME = "2013-05-24T00:00:00Z"; private static final String CHUNK_STS_PRE_SIGNATURE = "AWS4-ECDSA-P256-SHA256-PAYLOAD\n" + "20130524T000000Z\n" + "20130524/s3/aws4_request\n"; private static final String CHUNK1_STS_POST_SIGNATURE = "\ne3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\n" + "bf718b6f653bebc184e1479f1935b8da974d701b893afcf49e701f3e2f9f9c5a"; private static final String CHUNK2_STS_POST_SIGNATURE = "\ne3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\n" + "2edc986847e209b4016e141a6dc8716d3207350f416969382d431539bf292e4a"; private static final String CHUNK3_STS_POST_SIGNATURE = "\ne3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\n" + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; public static final String X_AMZ_TRAILER_SIGNATURE = "x-amz-trailer-signature:"; private static String TRAILING_HEADERS_STS_POST_SIGNATURE = "\n83d8f190334fb741bc8daf73c891689d320bd8017756bc730c540021ed48001f"; private static String TRAILING_HEADERS_STS_PRE_SIGNATURE = "AWS4-ECDSA-P256-SHA256-TRAILER\n" + "20130524T000000Z\n" + "20130524/s3/aws4_request\n"; private static final String CRLF = "\r\n"; private static final String SIGNATURE_KEY = "chunk-signature="; private static final int DATA_SIZE = 66560; /** * This content-length is actually incorrect; the correct calculated length should be 67064. However, since * the test case was developed using this number, it must be used when calculating the signatures or else * the test will fail verification. This is also the reason the sigv4a signer cannot be called directly in * a test since it would calculate a different content length. */ private static final int TOTAL_CONTENT_LENGTH = 66824; private static final int STREAM_CHUNK_SIZE = 65536; private static final int CHUNK2_SIZE = 1024; private static final byte[] data; private static final SimpleDateFormat DATE_FORMAT; @Mock SigningConfigProvider configProvider; CrtHttpRequestConverter converter; AwsCrt4aSigningAdapter adapter; AwsSigningConfig chunkedRequestSigningConfig; AwsSigningConfig chunkSigningConfig; ExecutionAttributes executionAttributes; static { DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); data = new byte[DATA_SIZE]; Arrays.fill(data, (byte) 'a'); } @Before public void setup() throws Exception { converter = new CrtHttpRequestConverter(); adapter = new AwsCrt4aSigningAdapter(); executionAttributes = buildBasicExecutionAttributes(); chunkedRequestSigningConfig = createChunkedRequestSigningConfig(executionAttributes); chunkSigningConfig = createChunkSigningConfig(executionAttributes); } @Test public void calling_adapter_APIs_directly_creates_correct_signatures() { byte[] previousSignature = createAndVerifyRequestSignature(defaultHttpRequest().build()); for (int i = 0; i < 3; i++) { byte[] currentSignature = adapter.signChunk(getChunkData(i), previousSignature, chunkSigningConfig); assertTrue(AwsSigningUtils.verifyRawSha256EcdsaSignature(createStringToSign(i, previousSignature), currentSignature, CHUNKED_SIGV4A_TEST_ECC_PUB_X, CHUNKED_SIGV4A_TEST_ECC_PUB_Y)); previousSignature = currentSignature; } } @Test public void using_a_request_stream_creates_correct_signatures() throws Exception { SdkHttpFullRequest request = defaultHttpRequest() .contentStreamProvider(() -> new ByteArrayInputStream(data)) .build(); byte[] requestSignature = createAndVerifyRequestSignature(request); AwsS3V4aChunkSigner chunkSigner = new AwsS3V4aChunkSigner(adapter, chunkSigningConfig); AwsChunkedEncodingConfig chunkedEncodingConfig = AwsChunkedEncodingConfig.builder() .chunkSize(STREAM_CHUNK_SIZE) .build(); AwsSignedChunkedEncodingInputStream stream = AwsSignedChunkedEncodingInputStream.builder() .inputStream(request.contentStreamProvider().get().newStream()) .awsChunkSigner(chunkSigner) .awsChunkedEncodingConfig(chunkedEncodingConfig) .headerSignature(new String(requestSignature, StandardCharsets.UTF_8)) .build(); ByteArrayOutputStream output = new ByteArrayOutputStream(); IOUtils.copy(stream, output); String result = new String(output.toByteArray(), StandardCharsets.UTF_8); assertChunks(result, 3, requestSignature, false); } @Test public void calling_adapter_APIs_directly_creates_correct_signatures_for_trailer_headers() throws Exception { SdkHttpFullRequest sdkHttpFullRequest = createChunkedTrailerTestRequest().build(); chunkedRequestSigningConfig.setAlgorithm(AwsSigningConfig.AwsSigningAlgorithm.SIGV4_ASYMMETRIC); chunkedRequestSigningConfig.setSignedBodyValue(AwsSigningConfig.AwsSignedBodyValue.STREAMING_AWS4_ECDSA_P256_SHA256_PAYLOAD_TRAILER); SdkSigningResult result = adapter.sign(sdkHttpFullRequest, chunkedRequestSigningConfig); byte[] requestSignature = result.getSignature(); assertTrue(AwsSigningUtils.verifySigv4aEcdsaSignature(converter.requestToCrt(sdkHttpFullRequest), CHUNKED_TRAILER_SIGV4A_CANONICAL_REQUEST, chunkedRequestSigningConfig, requestSignature, CHUNKED_SIGV4A_TEST_ECC_PUB_X, CHUNKED_SIGV4A_TEST_ECC_PUB_Y)); byte[] previousSignature = result.getSignature(); for (int i = 0; i < 3; i++) { byte[] currentSignature = adapter.signChunk(getChunkData(i), previousSignature, chunkSigningConfig); assertTrue(AwsSigningUtils.verifyRawSha256EcdsaSignature(createStringToSign(i, previousSignature), currentSignature, CHUNKED_SIGV4A_TEST_ECC_PUB_X, CHUNKED_SIGV4A_TEST_ECC_PUB_Y)); previousSignature = currentSignature; } updateTrailerHeaderSigningConfig(); Map<String, List<String>> trailerHeader = getTrailerHeaderMap(); AwsSigningResult trailingHeadersStringToSignResult = adapter.signTrailerHeaders(trailerHeader, previousSignature, chunkedRequestSigningConfig); byte[] trailingHeadersStringToSign = buildTrailingHeadersStringToSign(previousSignature, TRAILING_HEADERS_STS_POST_SIGNATURE); assertTrue(AwsSigningUtils.verifyRawSha256EcdsaSignature(trailingHeadersStringToSign, trailingHeadersStringToSignResult.getSignature(), CHUNKED_SIGV4A_TEST_ECC_PUB_X, CHUNKED_SIGV4A_TEST_ECC_PUB_Y)); } @Test public void using_a_request_stream_with_checksum_trailer_creates_correct_signatures() throws Exception { SdkHttpFullRequest request = defaultHttpRequest() .contentStreamProvider(() -> new ByteArrayInputStream(data)) .build(); byte[] requestSignature = createAndVerifyRequestSignature(request); AwsS3V4aChunkSigner chunkSigner = new AwsS3V4aChunkSigner(adapter, chunkSigningConfig); AwsChunkedEncodingConfig chunkedEncodingConfig = AwsChunkedEncodingConfig.builder() .chunkSize(STREAM_CHUNK_SIZE) .build(); AwsSignedChunkedEncodingInputStream stream = AwsSignedChunkedEncodingInputStream.builder() .checksumHeaderForTrailer("x-amz-checksum-crc32") .sdkChecksum(SdkChecksum.forAlgorithm(Algorithm.CRC32)) .inputStream(request.contentStreamProvider().get().newStream()) .awsChunkSigner(chunkSigner) .awsChunkedEncodingConfig(chunkedEncodingConfig) .headerSignature(new String(requestSignature, StandardCharsets.UTF_8)) .build(); ByteArrayOutputStream output = new ByteArrayOutputStream(); IOUtils.copy(stream, output); String result = new String(output.toByteArray(), StandardCharsets.UTF_8); assertChunks(result, 3, requestSignature, true); } private Map<String, List<String>> getTrailerHeaderMap() { Map<String, List<String>> trailerHeader = new LinkedHashMap<>(); trailerHeader.put("first", Collections.singletonList("1st")); trailerHeader.put("second", Collections.singletonList("2nd")); trailerHeader.put("third", Collections.singletonList("3rd")); return trailerHeader; } private void updateTrailerHeaderSigningConfig() { chunkedRequestSigningConfig.setAlgorithm(AwsSigningConfig.AwsSigningAlgorithm.SIGV4_ASYMMETRIC); chunkedRequestSigningConfig.setSignatureType(AwsSigningConfig.AwsSignatureType.HTTP_REQUEST_TRAILING_HEADERS); chunkedRequestSigningConfig.setSignedBodyHeader(AwsSigningConfig.AwsSignedBodyHeaderType.NONE); } private void assertChunks(String result, int numExpectedChunks, byte[] requestSignature, boolean isTrailerChecksum) { List<String> lines = Stream.of(result.split(CRLF)).collect(Collectors.toList()); assertThat(lines).hasSize(numExpectedChunks * 2 - 1 + (isTrailerChecksum ? 2 : 0)); byte[] previousSignature = requestSignature; int index = 0; for (String line : lines) { int chunk = lines.indexOf(line) / 2; if (lines.indexOf(line) % 2 == 0) { boolean isFinalTrailerSignature = isTrailerChecksum && index == lines.size() - 1; String signatureValue = isFinalTrailerSignature ? line.substring(line.indexOf(X_AMZ_TRAILER_SIGNATURE) + X_AMZ_TRAILER_SIGNATURE.length()) : line.substring(line.indexOf(SIGNATURE_KEY) + SIGNATURE_KEY.length()); byte[] currentSignature = signatureValue.getBytes(StandardCharsets.UTF_8); assertThat(signatureValue.length()).isEqualTo(AwsS3V4aChunkSigner.getSignatureLength()); if (!isFinalTrailerSignature) { assertTrue(AwsSigningUtils.verifyRawSha256EcdsaSignature(createStringToSign(chunk, previousSignature), currentSignature, CHUNKED_SIGV4A_TEST_ECC_PUB_X, CHUNKED_SIGV4A_TEST_ECC_PUB_Y)); } else { assertThat(signatureValue).hasSize(144); } previousSignature = currentSignature; } index++; } } private byte[] createAndVerifyRequestSignature(SdkHttpFullRequest request) { SdkSigningResult result = adapter.sign(request, chunkedRequestSigningConfig); byte[] requestSignature = result.getSignature(); assertTrue(AwsSigningUtils.verifySigv4aEcdsaSignature(converter.requestToCrt(request), CHUNKED_SIGV4A_CANONICAL_REQUEST, chunkedRequestSigningConfig, requestSignature, CHUNKED_SIGV4A_TEST_ECC_PUB_X, CHUNKED_SIGV4A_TEST_ECC_PUB_Y)); return requestSignature; } private ExecutionAttributes buildBasicExecutionAttributes() throws ParseException { ExecutionAttributes executionAttributes = new ExecutionAttributes(); executionAttributes.putAttribute(SIGNING_CLOCK, Clock.fixed(DATE_FORMAT.parse(CHUNKED_TEST_SIGNING_TIME).toInstant(), ZoneId.systemDefault())); executionAttributes.putAttribute(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME, CHUNKED_TEST_SERVICE); executionAttributes.putAttribute(AwsSignerExecutionAttribute.SIGNING_REGION, Region.of(CHUNKED_TEST_REGION)); executionAttributes.putAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS, AwsBasicCredentials.create(CHUNKED_ACCESS_KEY_ID, CHUNKED_SECRET_ACCESS_KEY)); executionAttributes.putAttribute(AwsSignerExecutionAttribute.SIGNER_DOUBLE_URL_ENCODE, false); return executionAttributes; } private AwsSigningConfig createChunkedRequestSigningConfig(ExecutionAttributes executionAttributes) throws Exception { AwsSigningConfig config = createBasicSigningConfig(executionAttributes); config.setUseDoubleUriEncode(executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNER_DOUBLE_URL_ENCODE)); config.setShouldNormalizeUriPath(true); config.setSignedBodyHeader(AwsSigningConfig.AwsSignedBodyHeaderType.X_AMZ_CONTENT_SHA256); config.setSignatureType(AwsSigningConfig.AwsSignatureType.HTTP_REQUEST_VIA_HEADERS); config.setSignedBodyValue(AwsSigningConfig.AwsSignedBodyValue.STREAMING_AWS4_ECDSA_P256_SHA256_PAYLOAD); return config; } private AwsSigningConfig createChunkSigningConfig(ExecutionAttributes executionAttributes) { AwsSigningConfig config = createBasicSigningConfig(executionAttributes); config.setSignedBodyHeader(AwsSigningConfig.AwsSignedBodyHeaderType.NONE); config.setSignatureType(AwsSigningConfig.AwsSignatureType.HTTP_REQUEST_CHUNK); return config; } private AwsSigningConfig createBasicSigningConfig(ExecutionAttributes executionAttributes) { AwsSigningConfig config = new AwsSigningConfig(); config.setCredentials(buildCredentials(executionAttributes)); config.setService(executionAttributes.getAttribute(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME)); config.setRegion(executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNING_REGION).id()); config.setTime(getSigningClock(executionAttributes).instant().toEpochMilli()); config.setAlgorithm(AwsSigningConfig.AwsSigningAlgorithm.SIGV4_ASYMMETRIC); return config; } private SdkHttpFullRequest.Builder defaultHttpRequest() { return SdkHttpFullRequest.builder() .method(SdkHttpMethod.PUT) .putHeader("x-amz-storage-class", "REDUCED_REDUNDANCY") .putHeader("Content-Encoding", "aws-chunked") .uri(URI.create("https://s3.amazonaws.com/examplebucket/chunkObject.txt")) .putHeader("x-amz-decoded-content-length", Integer.toString(DATA_SIZE)) .putHeader("Content-Length", Integer.toString(TOTAL_CONTENT_LENGTH)); } private SdkHttpFullRequest.Builder createChunkedTrailerTestRequest(){ return defaultHttpRequest().putHeader("x-amz-trailer", "first,second,third"); } private byte[] getChunkData(int chunk) { switch(chunk) { case 0: return Arrays.copyOfRange(data, 0, STREAM_CHUNK_SIZE); case 1: return Arrays.copyOfRange(data, STREAM_CHUNK_SIZE, STREAM_CHUNK_SIZE + CHUNK2_SIZE); default: return new byte[0]; } } private byte[] createStringToSign(int chunk, byte[] previousSignature) { switch(chunk) { case 0: return buildChunkStringToSign(previousSignature, CHUNK1_STS_POST_SIGNATURE); case 1: return buildChunkStringToSign(previousSignature, CHUNK2_STS_POST_SIGNATURE); default: return buildChunkStringToSign(previousSignature, CHUNK3_STS_POST_SIGNATURE); } } private byte[] buildChunkStringToSign(byte[] previousSignature, String stsPostSignature) { StringBuilder stsBuilder = new StringBuilder(); stsBuilder.append(CHUNK_STS_PRE_SIGNATURE); String signature = new String(previousSignature, StandardCharsets.UTF_8); int paddingIndex = signature.indexOf('*'); if (paddingIndex != -1) { signature = signature.substring(0, paddingIndex); } stsBuilder.append(signature); stsBuilder.append(stsPostSignature); return stsBuilder.toString().getBytes(StandardCharsets.UTF_8); } private byte[] buildTrailingHeadersStringToSign(byte[] previousSignature, String stsPostSignature) { StringBuilder stsBuilder = new StringBuilder(); stsBuilder.append(TRAILING_HEADERS_STS_PRE_SIGNATURE); String signature = new String(previousSignature, StandardCharsets.UTF_8); int paddingIndex = signature.indexOf('*'); if (paddingIndex != -1) { signature = signature.substring(0, paddingIndex); } stsBuilder.append(signature); stsBuilder.append(stsPostSignature); return stsBuilder.toString().getBytes(StandardCharsets.UTF_8); } }
1,801
0
Create_ds/aws-sdk-java-v2/core/auth-crt/src/test/java/software/amazon/awssdk/authcrt/signer
Create_ds/aws-sdk-java-v2/core/auth-crt/src/test/java/software/amazon/awssdk/authcrt/signer/internal/BaseSigningScopeTest.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.authcrt.signer.internal; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import software.amazon.awssdk.authcrt.signer.SignerTestUtils; import software.amazon.awssdk.authcrt.signer.SigningTestCase; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.RegionScope; /** * Functional tests for signing scope handling. These tests call the CRT native signer code. */ public abstract class BaseSigningScopeTest { @Test public void signing_withDefaultRegionScopeOnly_usesDefaultRegionScope() { SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase(); SdkHttpFullRequest signedRequest = signRequestWithScope(testCase, RegionScope.GLOBAL, null); String regionHeader = signedRequest.firstMatchingHeader("X-Amz-Region-Set").get(); assertThat(regionHeader).isEqualTo(RegionScope.GLOBAL.id()); } @Test public void presigning_withDefaultRegionScopeOnly_usesDefaultRegionScope() { SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase(); SdkHttpFullRequest signedRequest = presignRequestWithScope(testCase, RegionScope.GLOBAL, null); assertThat(signedRequest.rawQueryParameters().get("X-Amz-Region-Set")).containsExactly(RegionScope.GLOBAL.id()); } @Test public void signing_withDefaultScopeAndExplicitScope_usesExplicitScope() { SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase(); String expectdScope = "us-west-2"; SdkHttpFullRequest signedRequest = signRequestWithScope(testCase, RegionScope.GLOBAL, RegionScope.create(expectdScope)); String regionHeader = signedRequest.firstMatchingHeader("X-Amz-Region-Set").get(); assertThat(regionHeader).isEqualTo(expectdScope); } @Test public void presigning_withDefaultScopeAndExplicitScope_usesExplicitScope() { SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase(); String expectdScope = "us-west-2"; SdkHttpFullRequest signedRequest = presignRequestWithScope(testCase, RegionScope.GLOBAL, RegionScope.create(expectdScope)); assertThat(signedRequest.rawQueryParameters().get("X-Amz-Region-Set")).containsExactly(expectdScope); } @Test public void signing_withSigningRegionAndRegionScope_usesRegionScope() { SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase(); SdkHttpFullRequest signedRequest = signRequestWithScope(testCase, null, RegionScope.GLOBAL); String regionHeader = signedRequest.firstMatchingHeader("X-Amz-Region-Set").get(); assertThat(regionHeader).isEqualTo(RegionScope.GLOBAL.id()); } @Test public void presigning_withSigningRegionAndRegionScope_usesRegionScope() { SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase(); SdkHttpFullRequest signedRequest = presignRequestWithScope(testCase, null, RegionScope.GLOBAL); assertThat(signedRequest.rawQueryParameters().get("X-Amz-Region-Set")).containsExactly(RegionScope.GLOBAL.id()); } @Test public void signing_withSigningRegionOnly_usesSigningRegion() { SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase(); SdkHttpFullRequest signedRequest = signRequestWithScope(testCase, null, null); String regionHeader = signedRequest.firstMatchingHeader("X-Amz-Region-Set").get(); assertThat(regionHeader).isEqualTo(Region.AWS_GLOBAL.id()); } @Test public void presigning_withSigningRegionOnly_usesSigningRegion() { SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase(); SdkHttpFullRequest signedRequest = presignRequestWithScope(testCase, null, null); assertThat(signedRequest.rawQueryParameters().get("X-Amz-Region-Set")).containsExactly(Region.AWS_GLOBAL.id()); } protected abstract SdkHttpFullRequest signRequestWithScope(SigningTestCase testCase, RegionScope defaultRegionScope, RegionScope regionScope); protected abstract SdkHttpFullRequest presignRequestWithScope(SigningTestCase testCase, RegionScope defaultRegionScope, RegionScope regionScope); }
1,802
0
Create_ds/aws-sdk-java-v2/core/auth-crt/src/test/java/software/amazon/awssdk/authcrt/signer
Create_ds/aws-sdk-java-v2/core/auth-crt/src/test/java/software/amazon/awssdk/authcrt/signer/internal/AwsCrt4aSigningAdapterTest.java
package software.amazon.awssdk.authcrt.signer.internal; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertTrue; import static software.amazon.awssdk.auth.signer.internal.Aws4SignerUtils.calculateRequestContentLength; import static software.amazon.awssdk.authcrt.signer.SignerTestUtils.extractSignatureFromAuthHeader; import static software.amazon.awssdk.authcrt.signer.SignerTestUtils.extractSignedHeadersFromAuthHeader; import static software.amazon.awssdk.http.Header.CONTENT_LENGTH; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.signer.internal.chunkedencoding.AwsSignedChunkedEncodingInputStream; import software.amazon.awssdk.authcrt.signer.SignerTestUtils; import software.amazon.awssdk.authcrt.signer.SigningTestCase; import software.amazon.awssdk.authcrt.signer.internal.chunkedencoding.AwsS3V4aChunkSigner; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.internal.chunked.AwsChunkedEncodingConfig; import software.amazon.awssdk.crt.auth.signing.AwsSigningConfig; import software.amazon.awssdk.crt.auth.signing.AwsSigningResult; import software.amazon.awssdk.http.SdkHttpFullRequest; public class AwsCrt4aSigningAdapterTest { AwsCrt4aSigningAdapter crtSigningAdapter; SigningConfigProvider configProvider; @BeforeEach public void setup() { crtSigningAdapter = new AwsCrt4aSigningAdapter(); configProvider = new SigningConfigProvider(); } @Test public void signRequest_forHeader_works() { SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase(); ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase); SdkHttpFullRequest request = testCase.requestBuilder.build(); AwsSigningConfig signingConfig = configProvider.createCrtSigningConfig(executionAttributes); SdkHttpFullRequest signed = crtSigningAdapter.signRequest(request, signingConfig); String signatureValue = extractSignatureFromAuthHeader(signed); assertTrue(SignerTestUtils.verifyEcdsaSignature(request, testCase.expectedCanonicalRequest, signingConfig, signatureValue)); } @Test void sign_forHeader_works() { SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase(); ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase); SdkHttpFullRequest request = testCase.requestBuilder.build(); AwsSigningConfig signingConfig = configProvider.createCrtSigningConfig(executionAttributes); SdkSigningResult signed = crtSigningAdapter.sign(request, signingConfig); SdkHttpFullRequest signedRequest = signed.getSignedRequest(); String signatureValue = extractSignatureFromAuthHeader(signedRequest); assertTrue(SignerTestUtils.verifyEcdsaSignature(request, testCase.expectedCanonicalRequest, signingConfig, signatureValue)); } @Test public void sign_forChunkedHeader_works() { SigningTestCase testCase = SignerTestUtils.createBasicChunkedSigningTestCase(); ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase); SdkHttpFullRequest.Builder requestBuilder = testCase.requestBuilder; long originalContentLength = calculateRequestContentLength(requestBuilder); requestBuilder.putHeader("x-amz-decoded-content-length", Long.toString(originalContentLength)); requestBuilder.putHeader(CONTENT_LENGTH, Long.toString(AwsSignedChunkedEncodingInputStream.calculateStreamContentLength( originalContentLength, AwsS3V4aChunkSigner.getSignatureLength(), AwsChunkedEncodingConfig.create()))); SdkHttpFullRequest request = requestBuilder.build(); AwsSigningConfig signingConfig = configProvider.createS3CrtSigningConfig(executionAttributes); SdkSigningResult signingResult = crtSigningAdapter.sign(request, signingConfig); List<String> signedHeaders = extractSignedHeadersFromAuthHeader(signingResult.getSignedRequest()); assertThat(signedHeaders.size()).isEqualTo(7); assertThat(signedHeaders).contains("x-amz-decoded-content-length", "content-length"); byte[] data = new byte[10]; Arrays.fill(data, (byte) 0x61); AwsSigningConfig chunkConfig = configProvider.createChunkedSigningConfig(executionAttributes); byte[] chunkSignature = crtSigningAdapter.signChunk(data, signingResult.getSignature(), chunkConfig); assertThat(chunkSignature.length).isEqualTo(144); } @Test void sign_forTrailerHeader_works() { SigningTestCase testCase = SignerTestUtils.createBasicChunkedSigningTestCase(); ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase); SdkHttpFullRequest.Builder requestBuilder = testCase.requestBuilder; long originalContentLength = calculateRequestContentLength(requestBuilder); requestBuilder.putHeader("x-amz-decoded-content-length", Long.toString(originalContentLength)); requestBuilder.putHeader(CONTENT_LENGTH, Long.toString(AwsSignedChunkedEncodingInputStream.calculateStreamContentLength( originalContentLength, AwsS3V4aChunkSigner.getSignatureLength(), AwsChunkedEncodingConfig.create()))); SdkHttpFullRequest request = requestBuilder.build(); AwsSigningConfig signingConfig = configProvider.createS3CrtSigningConfig(executionAttributes); SdkSigningResult signingResult = crtSigningAdapter.sign(request, signingConfig); byte[] data = new byte[10]; Arrays.fill(data, (byte) 0x61); AwsSigningConfig chunkConfig = configProvider.createChunkedSigningConfig(executionAttributes); byte[] previousSignature = crtSigningAdapter.signChunk(data, signingResult.getSignature(), chunkConfig); AwsSigningResult trailerHeadersSignature = crtSigningAdapter .signTrailerHeaders(Collections.singletonMap("x-amz-checksum-crc32", Collections.singletonList("check4c==")), previousSignature, chunkConfig); assertThat(trailerHeadersSignature.getSignature()).hasSize(144); } }
1,803
0
Create_ds/aws-sdk-java-v2/core/auth-crt/src/test/java/software/amazon/awssdk/authcrt/signer
Create_ds/aws-sdk-java-v2/core/auth-crt/src/test/java/software/amazon/awssdk/authcrt/signer/internal/SigningConfigProviderTest.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.authcrt.signer.internal; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.time.Instant; import java.time.temporal.ChronoUnit; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute; import software.amazon.awssdk.auth.signer.S3SignerExecutionAttribute; import software.amazon.awssdk.auth.signer.internal.SignerConstant; import software.amazon.awssdk.authcrt.signer.SignerTestUtils; import software.amazon.awssdk.authcrt.signer.SigningTestCase; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.crt.auth.signing.AwsSigningConfig; public class SigningConfigProviderTest { SigningConfigProvider configProvider; @BeforeEach public void setup() { configProvider = new SigningConfigProvider(); } @Test public void testBasicHeaderSigningConfiguration() { SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase(); ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase); AwsSigningConfig signingConfig = configProvider.createCrtSigningConfig(executionAttributes); assertTrue(signingConfig.getAlgorithm() == AwsSigningConfig.AwsSigningAlgorithm.SIGV4_ASYMMETRIC); assertTrue(signingConfig.getSignatureType() == AwsSigningConfig.AwsSignatureType.HTTP_REQUEST_VIA_HEADERS); assertTrue(signingConfig.getRegion().equals(testCase.regionSet)); assertTrue(signingConfig.getService().equals(testCase.signingName)); assertTrue(signingConfig.getShouldNormalizeUriPath()); assertTrue(signingConfig.getUseDoubleUriEncode()); } @Test public void testBasicQuerySigningConfiguration() { SigningTestCase testCase = SignerTestUtils.createBasicQuerySigningTestCase(); ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase); AwsSigningConfig signingConfig = configProvider.createCrtPresigningConfig(executionAttributes); assertTrue(signingConfig.getAlgorithm() == AwsSigningConfig.AwsSigningAlgorithm.SIGV4_ASYMMETRIC); assertTrue(signingConfig.getSignatureType() == AwsSigningConfig.AwsSignatureType.HTTP_REQUEST_VIA_QUERY_PARAMS); assertTrue(signingConfig.getRegion().equals(testCase.regionSet)); assertTrue(signingConfig.getService().equals(testCase.signingName)); assertTrue(signingConfig.getShouldNormalizeUriPath()); assertTrue(signingConfig.getUseDoubleUriEncode()); assertTrue(signingConfig.getExpirationInSeconds() == SignerConstant.PRESIGN_URL_MAX_EXPIRATION_SECONDS); } @Test public void testQuerySigningExpirationConfiguration() { SigningTestCase testCase = SignerTestUtils.createBasicQuerySigningTestCase(); ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase); Instant expirationTime = testCase.signingTime.plus(900, ChronoUnit.SECONDS); executionAttributes.putAttribute(AwsSignerExecutionAttribute.PRESIGNER_EXPIRATION, expirationTime); AwsSigningConfig signingConfig = configProvider.createCrtPresigningConfig(executionAttributes); assertTrue(signingConfig.getExpirationInSeconds() == 900); } @Test public void testS3SigningConfiguration() { SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase(); ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase); executionAttributes.putAttribute(S3SignerExecutionAttribute.ENABLE_PAYLOAD_SIGNING, true); executionAttributes.putAttribute(AwsSignerExecutionAttribute.SIGNER_DOUBLE_URL_ENCODE, false); AwsSigningConfig signingConfig = configProvider.createS3CrtSigningConfig(executionAttributes); /* first check basic configuration */ assertTrue(signingConfig.getAlgorithm() == AwsSigningConfig.AwsSigningAlgorithm.SIGV4_ASYMMETRIC); assertTrue(signingConfig.getSignatureType() == AwsSigningConfig.AwsSignatureType.HTTP_REQUEST_VIA_HEADERS); assertTrue(signingConfig.getRegion().equals(testCase.regionSet)); assertTrue(signingConfig.getService().equals(testCase.signingName)); assertTrue(signingConfig.getShouldNormalizeUriPath()); assertFalse(signingConfig.getUseDoubleUriEncode()); /* body signing should be enabled */ assertTrue(signingConfig.getSignedBodyHeader() == AwsSigningConfig.AwsSignedBodyHeaderType.X_AMZ_CONTENT_SHA256); assertTrue(signingConfig.getSignedBodyValue() == null); /* try again with body signing explicitly disabled * we should still see the header but it should be using UNSIGNED_PAYLOAD for the value */ executionAttributes.putAttribute(S3SignerExecutionAttribute.ENABLE_PAYLOAD_SIGNING, false); signingConfig = configProvider.createS3CrtSigningConfig(executionAttributes); assertTrue(signingConfig.getSignedBodyHeader() == AwsSigningConfig.AwsSignedBodyHeaderType.X_AMZ_CONTENT_SHA256); } @Test public void testS3PresigningConfiguration() { SigningTestCase testCase = SignerTestUtils.createBasicQuerySigningTestCase(); ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase); executionAttributes.putAttribute(S3SignerExecutionAttribute.ENABLE_PAYLOAD_SIGNING, true); executionAttributes.putAttribute(AwsSignerExecutionAttribute.SIGNER_DOUBLE_URL_ENCODE, false); AwsSigningConfig signingConfig = configProvider.createS3CrtPresigningConfig(executionAttributes); /* first check basic configuration */ assertTrue(signingConfig.getAlgorithm() == AwsSigningConfig.AwsSigningAlgorithm.SIGV4_ASYMMETRIC); assertTrue(signingConfig.getSignatureType() == AwsSigningConfig.AwsSignatureType.HTTP_REQUEST_VIA_QUERY_PARAMS); assertTrue(signingConfig.getRegion().equals(testCase.regionSet)); assertTrue(signingConfig.getService().equals(testCase.signingName)); assertTrue(signingConfig.getShouldNormalizeUriPath()); assertFalse(signingConfig.getUseDoubleUriEncode()); /* body signing should be disabled and the body should be UNSIGNED_PAYLOAD */ assertTrue(signingConfig.getSignedBodyHeader() == AwsSigningConfig.AwsSignedBodyHeaderType.NONE); assertTrue(signingConfig.getSignedBodyValue() == AwsSigningConfig.AwsSignedBodyValue.UNSIGNED_PAYLOAD); } @Test public void testChunkedSigningConfiguration() { SigningTestCase testCase = SignerTestUtils.createBasicChunkedSigningTestCase(); ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase); executionAttributes.putAttribute(S3SignerExecutionAttribute.ENABLE_PAYLOAD_SIGNING, true); executionAttributes.putAttribute(AwsSignerExecutionAttribute.SIGNER_DOUBLE_URL_ENCODE, false); AwsSigningConfig signingConfig = configProvider.createChunkedSigningConfig(executionAttributes); assertThat(signingConfig.getCredentials()).isNotNull(); assertThat(signingConfig.getService()).isEqualTo(executionAttributes.getAttribute(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME)); assertThat(signingConfig.getRegion()).isEqualTo(executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNING_REGION).id()); assertThat(signingConfig.getTime()).isEqualTo(testCase.signingTime.toEpochMilli()); assertThat(signingConfig.getAlgorithm()).isEqualTo(AwsSigningConfig.AwsSigningAlgorithm.SIGV4_ASYMMETRIC); assertThat(signingConfig.getSignatureType()).isEqualTo(AwsSigningConfig.AwsSignatureType.HTTP_REQUEST_CHUNK); assertThat(signingConfig.getSignedBodyHeader()).isEqualTo(AwsSigningConfig.AwsSignedBodyHeaderType.NONE); } }
1,804
0
Create_ds/aws-sdk-java-v2/core/auth-crt/src/test/java/software/amazon/awssdk/authcrt/signer/internal
Create_ds/aws-sdk-java-v2/core/auth-crt/src/test/java/software/amazon/awssdk/authcrt/signer/internal/checksum/CrtBasedChecksumTest.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.authcrt.signer.internal.checksum; import static org.assertj.core.api.Assertions.assertThat; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.util.zip.Checksum; import org.junit.Test; import software.amazon.awssdk.core.checksums.Algorithm; import software.amazon.awssdk.core.checksums.SdkChecksum; import software.amazon.awssdk.core.internal.checksums.factory.CrtBasedChecksumProvider; import software.amazon.awssdk.crt.checksums.CRC32; import software.amazon.awssdk.crt.checksums.CRC32C; import software.amazon.awssdk.utils.BinaryUtils; public class CrtBasedChecksumTest { static final String TEST_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; @Test public void crtBasedCrc32ChecksumValues(){ Checksum checksum = CrtBasedChecksumProvider.createCrc32(); assertThat(checksum).isNotNull().isInstanceOf(CRC32.class); } @Test public void crtBasedCrc32_C_ChecksumValues(){ Checksum checksum = CrtBasedChecksumProvider.createCrc32C(); assertThat(checksum).isNotNull().isInstanceOf(CRC32C.class); } @Test public void crc32CheckSumValues() throws UnsupportedEncodingException { final SdkChecksum sdkChecksum = SdkChecksum.forAlgorithm(Algorithm.CRC32); final byte[] bytes = TEST_STRING.getBytes("UTF-8"); sdkChecksum.update(bytes, 0, bytes.length); assertThat(getAsString(sdkChecksum.getChecksumBytes())).isEqualTo("000000000000000000000000000000001fc2e6d2"); } @Test public void crc32_C_CheckSumValues() throws UnsupportedEncodingException { final SdkChecksum sdkChecksum = SdkChecksum.forAlgorithm(Algorithm.CRC32C); final byte[] bytes = TEST_STRING.getBytes("UTF-8"); sdkChecksum.update(bytes, 0, bytes.length); assertThat(getAsString(sdkChecksum.getChecksumBytes())).isEqualTo("00000000000000000000000000000000a245d57d"); } @Test public void validateEncodedBase64ForCrc32C() { SdkChecksum crc32c = SdkChecksum.forAlgorithm(Algorithm.CRC32C); crc32c.update("abc".getBytes(StandardCharsets.UTF_8)); String toBase64 = BinaryUtils.toBase64(crc32c.getChecksumBytes()); assertThat(toBase64).isEqualTo("Nks/tw=="); } @Test public void validateEncodedBase64ForCrc32() { SdkChecksum crc32 = SdkChecksum.forAlgorithm(Algorithm.CRC32); crc32.update("abc".getBytes(StandardCharsets.UTF_8)); String toBase64 = BinaryUtils.toBase64(crc32.getChecksumBytes()); assertThat(toBase64).isEqualTo("NSRBwg=="); } @Test public void validateMarkAndResetForCrc32() { SdkChecksum crc32 = SdkChecksum.forAlgorithm(Algorithm.CRC32); crc32.update("ab".getBytes(StandardCharsets.UTF_8)); crc32.mark(3); crc32.update("xyz".getBytes(StandardCharsets.UTF_8)); crc32.reset(); crc32.update("c".getBytes(StandardCharsets.UTF_8)); String toBase64 = BinaryUtils.toBase64(crc32.getChecksumBytes()); assertThat(toBase64).isEqualTo("NSRBwg=="); } @Test public void validateMarkAndResetForCrc32C() { SdkChecksum crc32c = SdkChecksum.forAlgorithm(Algorithm.CRC32C); crc32c.update("ab".getBytes(StandardCharsets.UTF_8)); crc32c.mark(3); crc32c.update("xyz".getBytes(StandardCharsets.UTF_8)); crc32c.reset(); crc32c.update("c".getBytes(StandardCharsets.UTF_8)); String toBase64 = BinaryUtils.toBase64(crc32c.getChecksumBytes()); assertThat(toBase64).isEqualTo("Nks/tw=="); } @Test public void validateMarkForCrc32C() { SdkChecksum crc32c = SdkChecksum.forAlgorithm(Algorithm.CRC32C); crc32c.update("Hello ".getBytes(StandardCharsets.UTF_8)); crc32c.mark(3); crc32c.update("world".getBytes(StandardCharsets.UTF_8)); String toBase64 = BinaryUtils.toBase64(crc32c.getChecksumBytes()); assertThat(toBase64).isEqualTo("crUfeA=="); } @Test public void validateMarkForCrc32() { SdkChecksum crc32 = SdkChecksum.forAlgorithm(Algorithm.CRC32); crc32.update("Hello ".getBytes(StandardCharsets.UTF_8)); crc32.mark(3); crc32.update("world".getBytes(StandardCharsets.UTF_8)); String toBase64 = BinaryUtils.toBase64(crc32.getChecksumBytes()); assertThat(toBase64).isEqualTo("i9aeUg=="); } private String getAsString(byte[] checksumBytes) { return String.format("%040x", new BigInteger(1, checksumBytes)); } }
1,805
0
Create_ds/aws-sdk-java-v2/core/auth-crt/src/main/java/software/amazon/awssdk/authcrt
Create_ds/aws-sdk-java-v2/core/auth-crt/src/main/java/software/amazon/awssdk/authcrt/signer/AwsCrtV4aSigner.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.authcrt.signer; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.authcrt.signer.internal.DefaultAwsCrtV4aSigner; import software.amazon.awssdk.core.signer.Presigner; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.regions.RegionScope; /** * Enables signing and presigning using Sigv4a (Asymmetric Sigv4) through an external API call to the AWS CRT * (Common RunTime) library. * <p/> * In CRT signing, payload signing is the default unless an override value is specified. */ @SdkPublicApi @Immutable @ThreadSafe public interface AwsCrtV4aSigner extends Signer, Presigner { /** * Create a default Aws4aSigner. */ static AwsCrtV4aSigner create() { return DefaultAwsCrtV4aSigner.create(); } static Builder builder() { return DefaultAwsCrtV4aSigner.builder(); } interface Builder { /** * The region scope that this signer will default to if not provided explicitly when the signer is invoked. * * @param defaultRegionScope The default region scope. * @return This builder for method chaining. */ Builder defaultRegionScope(RegionScope defaultRegionScope); AwsCrtV4aSigner build(); } }
1,806
0
Create_ds/aws-sdk-java-v2/core/auth-crt/src/main/java/software/amazon/awssdk/authcrt
Create_ds/aws-sdk-java-v2/core/auth-crt/src/main/java/software/amazon/awssdk/authcrt/signer/AwsCrtS3V4aSigner.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.authcrt.signer; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.authcrt.signer.internal.DefaultAwsCrtS3V4aSigner; import software.amazon.awssdk.core.signer.Presigner; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.regions.RegionScope; /** * Enables signing and presigning for S3 using Sigv4a (Asymmetric Sigv4) through an external API call to the AWS CRT * (Common RunTime) library. * <p/><b>S3 signing specifics</b><br> * For S3, the header "x-amz-sha256" must always be set for a request. * <p/> * S3 signs the payload signing if: * <ol> * <li> there's a body and an insecure protocol (HTTP) is used.</li> * <li> explicitly asked to via configuration/interceptor.</li> * </ol> * Otherwise, the body hash value will be UNSIGNED-PAYLOAD. * <p/> * See <a href="https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html"> * Amazon S3 Sigv4 documentation</a> for more detailed information. */ @SdkPublicApi @Immutable @ThreadSafe public interface AwsCrtS3V4aSigner extends Signer, Presigner { /** * Create a default AwsS34aSigner. */ static AwsCrtS3V4aSigner create() { return DefaultAwsCrtS3V4aSigner.create(); } static Builder builder() { return DefaultAwsCrtS3V4aSigner.builder(); } interface Builder { /** * The region scope that this signer will default to if not provided explicitly when the signer is invoked. * * @param defaultRegionScope The default region scope. * @return This builder for method chaining. */ Builder defaultRegionScope(RegionScope defaultRegionScope); AwsCrtS3V4aSigner build(); } }
1,807
0
Create_ds/aws-sdk-java-v2/core/auth-crt/src/main/java/software/amazon/awssdk/authcrt/signer
Create_ds/aws-sdk-java-v2/core/auth-crt/src/main/java/software/amazon/awssdk/authcrt/signer/internal/DefaultAwsCrtS3V4aSigner.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.authcrt.signer.internal; import static software.amazon.awssdk.auth.signer.internal.AbstractAwsS3V4Signer.STREAMING_UNSIGNED_PAYLOAD_TRAILER; import static software.amazon.awssdk.auth.signer.internal.Aws4SignerUtils.calculateRequestContentLength; import static software.amazon.awssdk.http.Header.CONTENT_LENGTH; import java.nio.charset.StandardCharsets; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.auth.credentials.CredentialUtils; import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute; import software.amazon.awssdk.auth.signer.S3SignerExecutionAttribute; import software.amazon.awssdk.auth.signer.internal.chunkedencoding.AwsSignedChunkedEncodingInputStream; import software.amazon.awssdk.auth.signer.params.SignerChecksumParams; import software.amazon.awssdk.authcrt.signer.AwsCrtS3V4aSigner; import software.amazon.awssdk.authcrt.signer.internal.chunkedencoding.AwsS3V4aChunkSigner; import software.amazon.awssdk.core.checksums.ChecksumSpecs; import software.amazon.awssdk.core.checksums.SdkChecksum; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.internal.chunked.AwsChunkedEncodingConfig; import software.amazon.awssdk.core.internal.util.HttpChecksumUtils; import software.amazon.awssdk.crt.auth.signing.AwsSigningConfig; import software.amazon.awssdk.http.ContentStreamProvider; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.regions.RegionScope; @SdkInternalApi public final class DefaultAwsCrtS3V4aSigner implements AwsCrtS3V4aSigner { private final AwsCrt4aSigningAdapter signerAdapter; private final SigningConfigProvider configProvider; private final RegionScope defaultRegionScope; DefaultAwsCrtS3V4aSigner(AwsCrt4aSigningAdapter signerAdapter, SigningConfigProvider signingConfigProvider) { this(signerAdapter, signingConfigProvider, null); } DefaultAwsCrtS3V4aSigner(AwsCrt4aSigningAdapter signerAdapter, SigningConfigProvider signingConfigProvider, RegionScope defaultRegionScope) { this.signerAdapter = signerAdapter; this.configProvider = signingConfigProvider; this.defaultRegionScope = defaultRegionScope; } private DefaultAwsCrtS3V4aSigner(BuilderImpl builder) { this(new AwsCrt4aSigningAdapter(), new SigningConfigProvider(), builder.defaultRegionScope); } public static AwsCrtS3V4aSigner create() { return builder().build(); } public static Builder builder() { return new BuilderImpl(); } @Override public SdkHttpFullRequest sign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes) { if (credentialsAreAnonymous(executionAttributes)) { return request; } ExecutionAttributes defaultsApplied = applyDefaults(executionAttributes); AwsSigningConfig requestSigningConfig = configProvider.createS3CrtSigningConfig(defaultsApplied); SignerChecksumParams signerChecksumParams = signerChecksumParamsFromAttributes(defaultsApplied); if (shouldSignPayload(request, defaultsApplied)) { SdkHttpFullRequest.Builder mutableRequest = request.toBuilder(); if (signerChecksumParams != null) { requestSigningConfig.setSignedBodyValue( AwsSigningConfig.AwsSignedBodyValue.STREAMING_AWS4_ECDSA_P256_SHA256_PAYLOAD_TRAILER); updateRequestWithTrailer(signerChecksumParams, mutableRequest); } else { requestSigningConfig.setSignedBodyValue( AwsSigningConfig.AwsSignedBodyValue.STREAMING_AWS4_ECDSA_P256_SHA256_PAYLOAD); } setHeaderContentLength(mutableRequest, signerChecksumParams); SdkSigningResult signingResult = signerAdapter.sign(mutableRequest.build(), requestSigningConfig); AwsSigningConfig chunkConfig = configProvider.createChunkedSigningConfig(defaultsApplied); return enablePayloadSigning(signingResult, chunkConfig, signerChecksumParams); } else { requestSigningConfig.setSignedBodyValue(signerChecksumParams != null ? STREAMING_UNSIGNED_PAYLOAD_TRAILER : AwsSigningConfig.AwsSignedBodyValue.UNSIGNED_PAYLOAD); return signerAdapter.signRequest(request, requestSigningConfig); } } private static SignerChecksumParams signerChecksumParamsFromAttributes(ExecutionAttributes executionAttributes) { ChecksumSpecs checksumSpecs = HttpChecksumUtils.checksumSpecWithRequestAlgorithm(executionAttributes).orElse(null); if (checksumSpecs == null) { return null; } return SignerChecksumParams.builder() .isStreamingRequest(checksumSpecs.isRequestStreaming()) .algorithm(checksumSpecs.algorithm()) .checksumHeaderName(checksumSpecs.headerName()).build(); } @Override public SdkHttpFullRequest presign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes) { if (credentialsAreAnonymous(executionAttributes)) { return request; } ExecutionAttributes defaultsApplied = applyDefaults(executionAttributes); return signerAdapter.signRequest(request, configProvider.createS3CrtPresigningConfig(defaultsApplied)); } private boolean credentialsAreAnonymous(ExecutionAttributes executionAttributes) { return CredentialUtils.isAnonymous(executionAttributes.getAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS)); } private boolean shouldSignPayload(SdkHttpFullRequest request, ExecutionAttributes executionAttributes) { if (!request.protocol().equals("https") && request.contentStreamProvider().isPresent()) { return true; } boolean payloadSigning = booleanValue(executionAttributes.getAttribute(S3SignerExecutionAttribute.ENABLE_PAYLOAD_SIGNING)); boolean chunkedEncoding = booleanValue(executionAttributes.getAttribute(S3SignerExecutionAttribute.ENABLE_CHUNKED_ENCODING)); return payloadSigning && chunkedEncoding; } private void setHeaderContentLength(SdkHttpFullRequest.Builder mutableRequest, SignerChecksumParams signerChecksumParams) { long originalContentLength = calculateRequestContentLength(mutableRequest); mutableRequest.putHeader("x-amz-decoded-content-length", Long.toString(originalContentLength)); String totalLength = Long.toString( AwsSignedChunkedEncodingInputStream.calculateStreamContentLength(originalContentLength, AwsS3V4aChunkSigner.getSignatureLength(), AwsChunkedEncodingConfig.create(), signerChecksumParams != null) + getChecksumTrailerLength(signerChecksumParams, AwsS3V4aChunkSigner.getSignatureLength())); mutableRequest.putHeader(CONTENT_LENGTH, totalLength); } private SdkHttpFullRequest enablePayloadSigning(SdkSigningResult signingResult, AwsSigningConfig chunkConfig, SignerChecksumParams signerChecksumParams) { SdkHttpFullRequest signedRequest = signingResult.getSignedRequest(); byte[] signature = signingResult.getSignature(); SdkHttpFullRequest.Builder mutableSignedRequest = signedRequest.toBuilder(); ContentStreamProvider streamProvider = mutableSignedRequest.contentStreamProvider(); AwsS3V4aChunkSigner chunkSigner = new AwsS3V4aChunkSigner(signerAdapter, chunkConfig); String checksumHeader = signerChecksumParams != null ? signerChecksumParams.checksumHeaderName() : null; SdkChecksum sdkChecksum = signerChecksumParams != null ? SdkChecksum.forAlgorithm(signerChecksumParams.algorithm()) : null; mutableSignedRequest.contentStreamProvider( () -> AwsSignedChunkedEncodingInputStream.builder() .inputStream(streamProvider.newStream()) .awsChunkSigner(chunkSigner) .checksumHeaderForTrailer(checksumHeader) .sdkChecksum(sdkChecksum) .headerSignature(new String(signature, StandardCharsets.UTF_8)) .awsChunkedEncodingConfig(AwsChunkedEncodingConfig.create()) .build()); return mutableSignedRequest.build(); } private boolean booleanValue(Boolean attribute) { return Boolean.TRUE.equals(attribute); } /** * Applies preconfigured defaults for values that are not present in {@code executionAttributes}. */ private ExecutionAttributes applyDefaults(ExecutionAttributes executionAttributes) { return applyDefaultRegionScope(executionAttributes); } private ExecutionAttributes applyDefaultRegionScope(ExecutionAttributes executionAttributes) { if (executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNING_REGION_SCOPE) != null) { return executionAttributes; } if (defaultRegionScope == null) { return executionAttributes; } return executionAttributes.copy() .putAttribute(AwsSignerExecutionAttribute.SIGNING_REGION_SCOPE, defaultRegionScope); } private static class BuilderImpl implements Builder { private RegionScope defaultRegionScope; @Override public Builder defaultRegionScope(RegionScope defaultRegionScope) { this.defaultRegionScope = defaultRegionScope; return this; } @Override public AwsCrtS3V4aSigner build() { return new DefaultAwsCrtS3V4aSigner(this); } } private static long getChecksumTrailerLength(SignerChecksumParams signerParams, int signatureLength) { return signerParams == null ? 0 : AwsSignedChunkedEncodingInputStream.calculateChecksumContentLength( signerParams.algorithm(), signerParams.checksumHeaderName(), signatureLength); } private static void updateRequestWithTrailer(SignerChecksumParams signerChecksumParams, SdkHttpFullRequest.Builder mutableRequest) { mutableRequest.putHeader("x-amz-trailer", signerChecksumParams.checksumHeaderName()); mutableRequest.appendHeader("Content-Encoding", "aws-chunked"); } }
1,808
0
Create_ds/aws-sdk-java-v2/core/auth-crt/src/main/java/software/amazon/awssdk/authcrt/signer
Create_ds/aws-sdk-java-v2/core/auth-crt/src/main/java/software/amazon/awssdk/authcrt/signer/internal/SdkSigningResult.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.authcrt.signer.internal; import java.util.Arrays; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.SdkHttpFullRequest; @SdkInternalApi public final class SdkSigningResult { private final SdkHttpFullRequest signedRequest; private final byte[] signature; public SdkSigningResult(byte[] signature, SdkHttpFullRequest signedRequest) { this.signature = Arrays.copyOf(signature, signature.length); this.signedRequest = signedRequest.toBuilder().build(); } public SdkHttpFullRequest getSignedRequest() { return this.signedRequest; } public byte[] getSignature() { return signature; } }
1,809
0
Create_ds/aws-sdk-java-v2/core/auth-crt/src/main/java/software/amazon/awssdk/authcrt/signer
Create_ds/aws-sdk-java-v2/core/auth-crt/src/main/java/software/amazon/awssdk/authcrt/signer/internal/DefaultAwsCrtV4aSigner.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.authcrt.signer.internal; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.auth.credentials.CredentialUtils; import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute; import software.amazon.awssdk.authcrt.signer.AwsCrtV4aSigner; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.regions.RegionScope; @SdkInternalApi public final class DefaultAwsCrtV4aSigner implements AwsCrtV4aSigner { private final AwsCrt4aSigningAdapter signer; private final SigningConfigProvider configProvider; private final RegionScope defaultRegionScope; private DefaultAwsCrtV4aSigner(BuilderImpl builder) { this(new AwsCrt4aSigningAdapter(), new SigningConfigProvider(), builder.defaultRegionScope); } DefaultAwsCrtV4aSigner(AwsCrt4aSigningAdapter signer, SigningConfigProvider configProvider, RegionScope defaultRegionScope) { this.signer = signer; this.configProvider = configProvider; this.defaultRegionScope = defaultRegionScope; } public static AwsCrtV4aSigner create() { return builder().build(); } public static Builder builder() { return new BuilderImpl(); } @Override public SdkHttpFullRequest sign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes) { if (CredentialUtils.isAnonymous(executionAttributes.getAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS))) { return request; } ExecutionAttributes defaultsApplied = applyDefaults(executionAttributes); return signer.signRequest(request, configProvider.createCrtSigningConfig(defaultsApplied)); } @Override public SdkHttpFullRequest presign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes) { ExecutionAttributes defaultsApplied = applyDefaults(executionAttributes); return signer.signRequest(request, configProvider.createCrtPresigningConfig(defaultsApplied)); } /** * Applies preconfigured defaults for values that are not present in {@code executionAttributes}. */ private ExecutionAttributes applyDefaults(ExecutionAttributes executionAttributes) { return applyDefaultRegionScope(executionAttributes); } private ExecutionAttributes applyDefaultRegionScope(ExecutionAttributes executionAttributes) { if (executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNING_REGION_SCOPE) != null) { return executionAttributes; } if (defaultRegionScope == null) { return executionAttributes; } return executionAttributes.copy() .putAttribute(AwsSignerExecutionAttribute.SIGNING_REGION_SCOPE, defaultRegionScope); } private static class BuilderImpl implements Builder { private RegionScope defaultRegionScope; @Override public Builder defaultRegionScope(RegionScope defaultRegionScope) { this.defaultRegionScope = defaultRegionScope; return this; } @Override public AwsCrtV4aSigner build() { return new DefaultAwsCrtV4aSigner(this); } } }
1,810
0
Create_ds/aws-sdk-java-v2/core/auth-crt/src/main/java/software/amazon/awssdk/authcrt/signer
Create_ds/aws-sdk-java-v2/core/auth-crt/src/main/java/software/amazon/awssdk/authcrt/signer/internal/AwsCrt4aSigningAdapter.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.authcrt.signer.internal; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.crt.auth.signing.AwsSigner; import software.amazon.awssdk.crt.auth.signing.AwsSigningConfig; import software.amazon.awssdk.crt.auth.signing.AwsSigningResult; import software.amazon.awssdk.crt.http.HttpHeader; import software.amazon.awssdk.crt.http.HttpRequest; import software.amazon.awssdk.crt.http.HttpRequestBodyStream; import software.amazon.awssdk.http.SdkHttpFullRequest; /** * This class mirrors the publicly available API of the AwsSigner class in CRT. */ @SdkInternalApi public class AwsCrt4aSigningAdapter { private final CrtHttpRequestConverter requestConverter; public AwsCrt4aSigningAdapter() { this.requestConverter = new CrtHttpRequestConverter(); } public SdkHttpFullRequest signRequest(SdkHttpFullRequest request, AwsSigningConfig signingConfig) { HttpRequest crtRequest = requestConverter.requestToCrt(SigningUtils.sanitizeSdkRequestForCrtSigning(request)); CompletableFuture<HttpRequest> future = AwsSigner.signRequest(crtRequest, signingConfig); try { HttpRequest signedRequest = future.get(); return requestConverter.crtRequestToHttp(request, signedRequest); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw SdkClientException.create("The thread got interrupted while attempting to sign request: " + e.getMessage(), e); } catch (Exception e) { throw SdkClientException.create("Unable to sign request: " + e.getMessage(), e); } } public SdkSigningResult sign(SdkHttpFullRequest request, AwsSigningConfig signingConfig) { HttpRequest crtRequest = requestConverter.requestToCrt(SigningUtils.sanitizeSdkRequestForCrtSigning(request)); CompletableFuture<AwsSigningResult> future = AwsSigner.sign(crtRequest, signingConfig); try { AwsSigningResult signingResult = future.get(); return requestConverter.crtResultToAws(request, signingResult); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw SdkClientException.create("The thread got interrupted while attempting to sign request: " + e.getMessage(), e); } catch (Exception e) { throw SdkClientException.create("Unable to sign request: " + e.getMessage(), e); } } public byte[] signChunk(byte[] chunkBody, byte[] previousSignature, AwsSigningConfig signingConfig) { HttpRequestBodyStream crtBody = requestConverter.toCrtStream(chunkBody); CompletableFuture<byte[]> future = AwsSigner.signChunk(crtBody, previousSignature, signingConfig); try { return future.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw SdkClientException.create("The thread got interrupted while attempting to sign request: " + e.getMessage(), e); } catch (Exception e) { throw SdkClientException.create("Unable to sign request: " + e.getMessage(), e); } } public AwsSigningResult signTrailerHeaders(Map<String, List<String>> headerMap, byte[] previousSignature, AwsSigningConfig signingConfig) { List<HttpHeader> httpHeaderList = headerMap.entrySet().stream().map(entry -> new HttpHeader( entry.getKey(), String.join(",", entry.getValue()))).collect(Collectors.toList()); // All the config remains the same as signing config except the Signature Type. AwsSigningConfig configCopy = signingConfig.clone(); configCopy.setSignatureType(AwsSigningConfig.AwsSignatureType.HTTP_REQUEST_TRAILING_HEADERS); CompletableFuture<AwsSigningResult> future = AwsSigner.sign(httpHeaderList, previousSignature, configCopy); try { return future.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw SdkClientException.create("The thread got interrupted while attempting to sign request: " + e.getMessage(), e); } catch (Exception e) { throw SdkClientException.create("Unable to sign request: " + e.getMessage(), e); } } }
1,811
0
Create_ds/aws-sdk-java-v2/core/auth-crt/src/main/java/software/amazon/awssdk/authcrt/signer
Create_ds/aws-sdk-java-v2/core/auth-crt/src/main/java/software/amazon/awssdk/authcrt/signer/internal/CrtHttpRequestConverter.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.authcrt.signer.internal; import static java.lang.Math.min; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.crt.auth.signing.AwsSigningResult; import software.amazon.awssdk.crt.http.HttpHeader; import software.amazon.awssdk.crt.http.HttpRequest; import software.amazon.awssdk.crt.http.HttpRequestBodyStream; import software.amazon.awssdk.http.ContentStreamProvider; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.utils.StringUtils; import software.amazon.awssdk.utils.http.SdkHttpUtils; @SdkInternalApi public final class CrtHttpRequestConverter { private static final String SLASH = "/"; private static final String HOST_HEADER = "Host"; private static final int READ_BUFFER_SIZE = 4096; public CrtHttpRequestConverter() { } public HttpRequest requestToCrt(SdkHttpFullRequest inputRequest) { String method = inputRequest.method().name(); String encodedPath = encodedPathToCrtFormat(inputRequest.encodedPath()); String encodedQueryString = inputRequest.encodedQueryParameters().map(value -> "?" + value).orElse(""); HttpHeader[] crtHeaderArray = createHttpHeaderArray(inputRequest); Optional<ContentStreamProvider> contentProvider = inputRequest.contentStreamProvider(); HttpRequestBodyStream crtInputStream = null; if (contentProvider.isPresent()) { crtInputStream = new CrtHttpRequestConverter.CrtInputStream(contentProvider.get()); } return new HttpRequest(method, encodedPath + encodedQueryString, crtHeaderArray, crtInputStream); } public SdkHttpFullRequest crtRequestToHttp(SdkHttpFullRequest inputRequest, HttpRequest signedCrtRequest) { SdkHttpFullRequest.Builder builder = inputRequest.toBuilder(); builder.clearHeaders(); for (HttpHeader header : signedCrtRequest.getHeaders()) { builder.appendHeader(header.getName(), header.getValue()); } URI fullUri = null; try { String portString = SdkHttpUtils.isUsingStandardPort(builder.protocol(), builder.port()) ? "" : ":" + builder.port(); String encodedPath = encodedPathFromCrtFormat(inputRequest.encodedPath(), signedCrtRequest.getEncodedPath()); String fullUriString = builder.protocol() + "://" + builder.host() + portString + encodedPath; fullUri = new URI(fullUriString); } catch (URISyntaxException e) { return null; } builder.encodedPath(fullUri.getRawPath()); String remainingQuery = fullUri.getQuery(); builder.clearQueryParameters(); while (remainingQuery != null && remainingQuery.length() > 0) { int nextQuery = remainingQuery.indexOf('&'); int nextAssign = remainingQuery.indexOf('='); if (nextAssign < nextQuery || (nextAssign >= 0 && nextQuery < 0)) { String queryName = remainingQuery.substring(0, nextAssign); String queryValue = remainingQuery.substring(nextAssign + 1); if (nextQuery >= 0) { queryValue = remainingQuery.substring(nextAssign + 1, nextQuery); } builder.appendRawQueryParameter(queryName, queryValue); } else { String queryName = remainingQuery; if (nextQuery >= 0) { queryName = remainingQuery.substring(0, nextQuery); } builder.appendRawQueryParameter(queryName, null); } if (nextQuery >= 0) { remainingQuery = remainingQuery.substring(nextQuery + 1); } else { break; } } return builder.build(); } public SdkSigningResult crtResultToAws(SdkHttpFullRequest originalRequest, AwsSigningResult signingResult) { SdkHttpFullRequest sdkHttpFullRequest = crtRequestToHttp(originalRequest, signingResult.getSignedRequest()); return new SdkSigningResult(signingResult.getSignature(), sdkHttpFullRequest); } public HttpRequestBodyStream toCrtStream(byte[] data) { return new CrtByteArrayInputStream(data); } private HttpHeader[] createHttpHeaderArray(SdkHttpFullRequest request) { List<HttpHeader> crtHeaderList = new ArrayList<>(request.numHeaders() + 2); // Set Host Header if needed if (!request.firstMatchingHeader(HOST_HEADER).isPresent()) { crtHeaderList.add(new HttpHeader(HOST_HEADER, request.host())); } // Add the rest of the Headers request.forEachHeader((name, values) -> { for (String val : values) { HttpHeader h = new HttpHeader(name, val); crtHeaderList.add(h); } }); return crtHeaderList.toArray(new HttpHeader[0]); } private static String encodedPathToCrtFormat(String sdkEncodedPath) { if (StringUtils.isEmpty(sdkEncodedPath)) { return "/"; } return sdkEncodedPath; } private static String encodedPathFromCrtFormat(String sdkEncodedPath, String crtEncodedPath) { if (SLASH.equals(crtEncodedPath) && StringUtils.isEmpty(sdkEncodedPath)) { return ""; } return crtEncodedPath; } private static class CrtByteArrayInputStream implements HttpRequestBodyStream { private byte[] data; private byte[] readBuffer; private ByteArrayInputStream providerStream; CrtByteArrayInputStream(byte[] data) { this.data = data; this.readBuffer = new byte[READ_BUFFER_SIZE]; } @Override public boolean sendRequestBody(ByteBuffer bodyBytesOut) { int read = 0; try { if (providerStream == null) { createNewStream(); } int toRead = min(READ_BUFFER_SIZE, bodyBytesOut.remaining()); read = providerStream.read(readBuffer, 0, toRead); if (read > 0) { bodyBytesOut.put(readBuffer, 0, read); } } catch (IOException ioe) { throw new RuntimeException(ioe); } return read < 0; } @Override public boolean resetPosition() { try { createNewStream(); } catch (IOException ioe) { throw new RuntimeException(ioe); } return true; } private void createNewStream() throws IOException { if (providerStream != null) { providerStream.close(); } providerStream = new ByteArrayInputStream(data); } } private static class CrtInputStream implements HttpRequestBodyStream { private ContentStreamProvider provider; private InputStream providerStream; private byte[] readBuffer; CrtInputStream(ContentStreamProvider provider) { this.provider = provider; this.readBuffer = new byte[READ_BUFFER_SIZE]; } @Override public boolean sendRequestBody(ByteBuffer bodyBytesOut) { int read = 0; try { if (providerStream == null) { createNewStream(); } int toRead = min(READ_BUFFER_SIZE, bodyBytesOut.remaining()); read = providerStream.read(readBuffer, 0, toRead); if (read > 0) { bodyBytesOut.put(readBuffer, 0, read); } } catch (IOException ioe) { throw new RuntimeException(ioe); } return read < 0; } @Override public boolean resetPosition() { if (provider == null) { throw new IllegalStateException("Cannot reset position while provider is null"); } try { createNewStream(); } catch (IOException ioe) { throw new RuntimeException(ioe); } return true; } private void createNewStream() throws IOException { if (provider == null) { throw new IllegalStateException("Cannot create a new stream while provider is null"); } if (providerStream != null) { providerStream.close(); } providerStream = provider.newStream(); } } }
1,812
0
Create_ds/aws-sdk-java-v2/core/auth-crt/src/main/java/software/amazon/awssdk/authcrt/signer
Create_ds/aws-sdk-java-v2/core/auth-crt/src/main/java/software/amazon/awssdk/authcrt/signer/internal/SigningConfigProvider.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.authcrt.signer.internal; import static software.amazon.awssdk.authcrt.signer.internal.SigningUtils.buildCredentials; import static software.amazon.awssdk.authcrt.signer.internal.SigningUtils.getSigningClock; import java.time.Duration; import java.time.Instant; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute; import software.amazon.awssdk.auth.signer.internal.SignerConstant; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.crt.auth.signing.AwsSigningConfig; import software.amazon.awssdk.regions.RegionScope; @SdkInternalApi public class SigningConfigProvider { private static final Boolean DEFAULT_DOUBLE_URL_ENCODE = Boolean.TRUE; private static final Boolean DEFAULT_PATH_NORMALIZATION = Boolean.TRUE; public SigningConfigProvider() { } public AwsSigningConfig createCrtSigningConfig(ExecutionAttributes executionAttributes) { AwsSigningConfig signingConfig = createDefaultRequestConfig(executionAttributes); signingConfig.setSignatureType(AwsSigningConfig.AwsSignatureType.HTTP_REQUEST_VIA_HEADERS); return signingConfig; } public AwsSigningConfig createCrtPresigningConfig(ExecutionAttributes executionAttributes) { AwsSigningConfig signingConfig = createPresigningConfig(executionAttributes); signingConfig.setSignatureType(AwsSigningConfig.AwsSignatureType.HTTP_REQUEST_VIA_QUERY_PARAMS); return signingConfig; } public AwsSigningConfig createS3CrtSigningConfig(ExecutionAttributes executionAttributes) { AwsSigningConfig signingConfig = createDefaultRequestConfig(executionAttributes); signingConfig.setSignedBodyHeader(AwsSigningConfig.AwsSignedBodyHeaderType.X_AMZ_CONTENT_SHA256); signingConfig.setSignatureType(AwsSigningConfig.AwsSignatureType.HTTP_REQUEST_VIA_HEADERS); return signingConfig; } public AwsSigningConfig createS3CrtPresigningConfig(ExecutionAttributes executionAttributes) { AwsSigningConfig signingConfig = createPresigningConfig(executionAttributes); signingConfig.setSignedBodyHeader(AwsSigningConfig.AwsSignedBodyHeaderType.NONE); signingConfig.setSignedBodyValue(AwsSigningConfig.AwsSignedBodyValue.UNSIGNED_PAYLOAD); signingConfig.setSignatureType(AwsSigningConfig.AwsSignatureType.HTTP_REQUEST_VIA_QUERY_PARAMS); return signingConfig; } public AwsSigningConfig createChunkedSigningConfig(ExecutionAttributes executionAttributes) { AwsSigningConfig signingConfig = createStringToSignConfig(executionAttributes); signingConfig.setSignatureType(AwsSigningConfig.AwsSignatureType.HTTP_REQUEST_CHUNK); signingConfig.setSignedBodyHeader(AwsSigningConfig.AwsSignedBodyHeaderType.NONE); return signingConfig; } private AwsSigningConfig createPresigningConfig(ExecutionAttributes executionAttributes) { Optional<Instant> expirationTime = Optional.ofNullable( executionAttributes.getAttribute(AwsSignerExecutionAttribute.PRESIGNER_EXPIRATION)); long expirationInSeconds = expirationTime .map(end -> Math.max(0, Duration.between(getSigningClock(executionAttributes).instant(), end).getSeconds())) .orElse(SignerConstant.PRESIGN_URL_MAX_EXPIRATION_SECONDS); AwsSigningConfig signingConfig = createDefaultRequestConfig(executionAttributes); signingConfig.setExpirationInSeconds(expirationInSeconds); return signingConfig; } private AwsSigningConfig createDefaultRequestConfig(ExecutionAttributes executionAttributes) { AwsSigningConfig signingConfig = createStringToSignConfig(executionAttributes); if (executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNER_NORMALIZE_PATH) != null) { signingConfig.setShouldNormalizeUriPath( executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNER_NORMALIZE_PATH)); } else { signingConfig.setShouldNormalizeUriPath(DEFAULT_PATH_NORMALIZATION); } if (executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNER_DOUBLE_URL_ENCODE) != null) { signingConfig.setUseDoubleUriEncode( executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNER_DOUBLE_URL_ENCODE)); } else { signingConfig.setUseDoubleUriEncode(DEFAULT_DOUBLE_URL_ENCODE); } return signingConfig; } private AwsSigningConfig createStringToSignConfig(ExecutionAttributes executionAttributes) { AwsSigningConfig signingConfig = new AwsSigningConfig(); signingConfig.setCredentials(buildCredentials(executionAttributes)); signingConfig.setService(executionAttributes.getAttribute(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME)); signingConfig.setRegion(getRegion(executionAttributes)); signingConfig.setAlgorithm(AwsSigningConfig.AwsSigningAlgorithm.SIGV4_ASYMMETRIC); signingConfig.setTime(getSigningClock(executionAttributes).instant().toEpochMilli()); return signingConfig; } private String getRegion(ExecutionAttributes executionAttributes) { RegionScope signingScope = executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNING_REGION_SCOPE); return signingScope == null ? executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNING_REGION).id() : signingScope.id(); } }
1,813
0
Create_ds/aws-sdk-java-v2/core/auth-crt/src/main/java/software/amazon/awssdk/authcrt/signer
Create_ds/aws-sdk-java-v2/core/auth-crt/src/main/java/software/amazon/awssdk/authcrt/signer/internal/SigningUtils.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.authcrt.signer.internal; import java.nio.charset.StandardCharsets; import java.time.Clock; import java.time.Duration; import java.util.Optional; import java.util.Set; import java.util.TreeSet; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentials; import software.amazon.awssdk.auth.credentials.AwsSessionCredentials; import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute; import software.amazon.awssdk.core.interceptor.ExecutionAttribute; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.crt.auth.credentials.Credentials; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.utils.StringUtils; import software.amazon.awssdk.utils.http.SdkHttpUtils; @SdkInternalApi public class SigningUtils { /** * Attribute allowing the user to inject a clock that will be used for the signing timestamp */ public static final ExecutionAttribute<Clock> SIGNING_CLOCK = new ExecutionAttribute<>("SigningClock"); private static final String BODY_HASH_NAME = "x-amz-content-sha256"; private static final String DATE_NAME = "X-Amz-Date"; private static final String AUTHORIZATION_NAME = "Authorization"; private static final String REGION_SET_NAME = "X-amz-region-set"; private static final String SIGNATURE_NAME = "X-Amz-Signature"; private static final String CREDENTIAL_NAME = "X-Amz-Credential"; private static final String ALGORITHM_NAME = "X-Amz-Algorithm"; private static final String SIGNED_HEADERS_NAME = "X-Amz-SignedHeaders"; private static final String EXPIRES_NAME = "X-Amz-Expires"; private static final Set<String> FORBIDDEN_HEADERS = buildForbiddenHeaderSet(); private static final Set<String> FORBIDDEN_PARAMS = buildForbiddenQueryParamSet(); private static final String HOST_HEADER = "Host"; private SigningUtils() { } public static Credentials buildCredentials(ExecutionAttributes executionAttributes) { AwsCredentials sdkCredentials = SigningUtils.sanitizeCredentials( executionAttributes.getAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS)); byte[] sessionToken = null; if (sdkCredentials instanceof AwsSessionCredentials) { AwsSessionCredentials sessionCreds = (AwsSessionCredentials) sdkCredentials; sessionToken = sessionCreds.sessionToken().getBytes(StandardCharsets.UTF_8); } return new Credentials(sdkCredentials.accessKeyId().getBytes(StandardCharsets.UTF_8), sdkCredentials.secretAccessKey().getBytes(StandardCharsets.UTF_8), sessionToken); } public static Clock getSigningClock(ExecutionAttributes executionAttributes) { Clock clock = executionAttributes.getAttribute(SIGNING_CLOCK); if (clock != null) { return clock; } Clock baseClock = Clock.systemUTC(); Optional<Integer> timeOffset = Optional.ofNullable(executionAttributes.getAttribute( AwsSignerExecutionAttribute.TIME_OFFSET)); return timeOffset .map(offset -> Clock.offset(baseClock, Duration.ofSeconds(-offset))) .orElse(baseClock); } public static AwsCredentials sanitizeCredentials(AwsCredentials credentials) { String accessKeyId = StringUtils.trim(credentials.accessKeyId()); String secretKey = StringUtils.trim(credentials.secretAccessKey()); if (credentials instanceof AwsSessionCredentials) { AwsSessionCredentials sessionCredentials = (AwsSessionCredentials) credentials; return AwsSessionCredentials.create(accessKeyId, secretKey, StringUtils.trim(sessionCredentials.sessionToken())); } return AwsBasicCredentials.create(accessKeyId, secretKey); } public static SdkHttpFullRequest sanitizeSdkRequestForCrtSigning(SdkHttpFullRequest request) { SdkHttpFullRequest.Builder builder = request.toBuilder(); // Ensure path is non-empty String path = builder.encodedPath(); if (path == null || path.length() == 0) { builder.encodedPath("/"); } builder.clearHeaders(); // Filter headers that will cause signing to fail request.forEachHeader((name, value) -> { if (!FORBIDDEN_HEADERS.contains(name)) { builder.putHeader(name, value); } }); // Add host, which must be signed. We ignore any pre-existing Host header to match the behavior of the SigV4 signer. String hostHeader = SdkHttpUtils.isUsingStandardPort(request.protocol(), request.port()) ? request.host() : request.host() + ":" + request.port(); builder.putHeader(HOST_HEADER, hostHeader); builder.clearQueryParameters(); // Filter query parameters that will cause signing to fail request.forEachRawQueryParameter((key, value) -> { if (!FORBIDDEN_PARAMS.contains(key)) { builder.putRawQueryParameter(key, value); } }); return builder.build(); } private static Set<String> buildForbiddenHeaderSet() { Set<String> forbiddenHeaders = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER); forbiddenHeaders.add(BODY_HASH_NAME); forbiddenHeaders.add(DATE_NAME); forbiddenHeaders.add(AUTHORIZATION_NAME); forbiddenHeaders.add(REGION_SET_NAME); return forbiddenHeaders; } private static Set<String> buildForbiddenQueryParamSet() { Set<String> forbiddenParams = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER); forbiddenParams.add(SIGNATURE_NAME); forbiddenParams.add(DATE_NAME); forbiddenParams.add(CREDENTIAL_NAME); forbiddenParams.add(ALGORITHM_NAME); forbiddenParams.add(SIGNED_HEADERS_NAME); forbiddenParams.add(REGION_SET_NAME); forbiddenParams.add(EXPIRES_NAME); return forbiddenParams; } }
1,814
0
Create_ds/aws-sdk-java-v2/core/auth-crt/src/main/java/software/amazon/awssdk/authcrt/signer/internal
Create_ds/aws-sdk-java-v2/core/auth-crt/src/main/java/software/amazon/awssdk/authcrt/signer/internal/chunkedencoding/AwsS3V4aChunkSigner.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.authcrt.signer.internal.chunkedencoding; import java.nio.charset.StandardCharsets; import java.util.Collections; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.auth.signer.internal.chunkedencoding.AwsChunkSigner; import software.amazon.awssdk.authcrt.signer.internal.AwsCrt4aSigningAdapter; import software.amazon.awssdk.crt.auth.signing.AwsSigningConfig; import software.amazon.awssdk.crt.auth.signing.AwsSigningResult; import software.amazon.awssdk.utils.BinaryUtils; /** * An implementation of AwsChunkSigner that can calculate a Sigv4a compatible chunk signature. */ @SdkInternalApi public class AwsS3V4aChunkSigner implements AwsChunkSigner { private static final int SIGNATURE_LENGTH = 144; private final AwsCrt4aSigningAdapter aws4aSigner; private final AwsSigningConfig signingConfig; public AwsS3V4aChunkSigner(AwsCrt4aSigningAdapter aws4aSigner, AwsSigningConfig signingConfig) { this.aws4aSigner = aws4aSigner; this.signingConfig = signingConfig; } @Override public String signChunk(byte[] chunkData, String previousSignature) { byte[] chunkSignature = aws4aSigner.signChunk(chunkData, previousSignature.getBytes(StandardCharsets.UTF_8), signingConfig); return new String(chunkSignature, StandardCharsets.UTF_8); } @Override public String signChecksumChunk(byte[] calculatedChecksum, String previousSignature, String checksumHeaderForTrailer) { AwsSigningResult awsSigningResult = aws4aSigner.signTrailerHeaders( Collections.singletonMap(checksumHeaderForTrailer, Collections.singletonList(BinaryUtils.toBase64(calculatedChecksum))), previousSignature.getBytes(StandardCharsets.UTF_8), signingConfig); return awsSigningResult != null ? new String(awsSigningResult.getSignature(), StandardCharsets.UTF_8) : null; } public static int getSignatureLength() { return SIGNATURE_LENGTH; } }
1,815
0
Create_ds/aws-sdk-java-v2/core/annotations/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/annotations/src/main/java/software/amazon/awssdk/annotations/ThreadSafe.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.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * The class to which this annotation is applied is thread-safe. This means that * no sequences of accesses (reads and writes to public fields, calls to public methods) * may put the object into an invalid state, regardless of the interleaving of those actions * by the runtime, and without requiring any additional synchronization or coordination on the * part of the caller. * <p> * Based on code developed by Brian Goetz and Tim Peierls and concepts * published in 'Java Concurrency in Practice' by Brian Goetz, Tim Peierls, * Joshua Bloch, Joseph Bowbeer, David Holmes and Doug Lea. * * @see NotThreadSafe */ @Documented @Target(ElementType.TYPE) @Retention(RetentionPolicy.CLASS) // The original version used RUNTIME @SdkProtectedApi public @interface ThreadSafe { }
1,816
0
Create_ds/aws-sdk-java-v2/core/annotations/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/annotations/src/main/java/software/amazon/awssdk/annotations/SdkTestInternalApi.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.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Target; /** * Marker interface for methods used by test code in the same module. Methods/Constructors annotated * with this method should not be accessed in production code. This annotation should be used * sparingly as it's a code smell to need access to internal data/functionality to properly unit * test a class. Typically there is a better way to test a class. * <p> * TODO: Write a linter that makes sure only test code depends on methods or constructors annotated * with this method */ @Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.FIELD, ElementType.TYPE}) @SdkProtectedApi public @interface SdkTestInternalApi { }
1,817
0
Create_ds/aws-sdk-java-v2/core/annotations/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/annotations/src/main/java/software/amazon/awssdk/annotations/Mutable.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.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * The class to which this annotation is applied is explicitly mutable, * meaning that its state is subject to change between calls. Mutable * classes offer no inherent guarantees on thread-safety. Where possible, * classes may be further annotated as either {@link ThreadSafe} or * {@link NotThreadSafe}. * * @see Immutable */ @Documented @Target(ElementType.TYPE) @Retention(RetentionPolicy.CLASS) @SdkProtectedApi public @interface Mutable { }
1,818
0
Create_ds/aws-sdk-java-v2/core/annotations/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/annotations/src/main/java/software/amazon/awssdk/annotations/SdkProtectedApi.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.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Target; /** * Marker for elements that should only be accessed by the generated clients and not users of the * SDK. Do not make breaking changes to these APIs - they won't directly break customers, but * they'll break old versions of generated clients. * <p> * TODO: Write a linter that makes sure generated code only depends on public or * {@code @InternalApi} classes. */ @Target({ElementType.PACKAGE, ElementType.TYPE, ElementType.FIELD, ElementType.CONSTRUCTOR, ElementType.METHOD}) @SdkProtectedApi public @interface SdkProtectedApi { }
1,819
0
Create_ds/aws-sdk-java-v2/core/annotations/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/annotations/src/main/java/software/amazon/awssdk/annotations/Immutable.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.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * The class to which this annotation is applied is immutable. This means that * its state cannot be seen to change by callers, which implies that * <ul> * <li> all public fields are final, </li> * <li> all public final reference fields refer to other immutable objects, and </li> * <li> constructors and methods do not publish references to any internal state * which is potentially mutable by the implementation. </li> * </ul> * Immutable objects may still have internal mutable state for purposes of performance * optimization; some state variables may be lazily computed, so long as they are computed * from immutable state and that callers cannot tell the difference. * <p> * Immutable objects are inherently thread-safe; they may be passed between threads or * published without synchronization. * <p> * Based on code developed by Brian Goetz and Tim Peierls and concepts * published in 'Java Concurrency in Practice' by Brian Goetz, Tim Peierls, * Joshua Bloch, Joseph Bowbeer, David Holmes and Doug Lea. * * @see Mutable */ @Documented @Target(ElementType.TYPE) @Retention(RetentionPolicy.CLASS) // The original version used RUNTIME @SdkProtectedApi public @interface Immutable { }
1,820
0
Create_ds/aws-sdk-java-v2/core/annotations/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/annotations/src/main/java/software/amazon/awssdk/annotations/SdkPreviewApi.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.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Target; /** * Marker interface for preview and experimental APIs. Breaking changes may be * introduced to elements marked as {@link SdkPreviewApi}. Users of the SDK * should assume that anything annotated as preview will change or break, and * <b>should not</b> use them in production. */ @Target({ElementType.PACKAGE, ElementType.TYPE, ElementType.FIELD, ElementType.CONSTRUCTOR, ElementType.METHOD}) @SdkProtectedApi public @interface SdkPreviewApi { }
1,821
0
Create_ds/aws-sdk-java-v2/core/annotations/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/annotations/src/main/java/software/amazon/awssdk/annotations/NotThreadSafe.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.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * The class to which this annotation is applied is not thread-safe. * This annotation primarily exists for clarifying the non-thread-safety of a class * that might otherwise be assumed to be thread-safe, despite the fact that it is a bad * idea to assume a class is thread-safe without good reason. * <p> * Based on code developed by Brian Goetz and Tim Peierls and concepts * published in 'Java Concurrency in Practice' by Brian Goetz, Tim Peierls, * Joshua Bloch, Joseph Bowbeer, David Holmes and Doug Lea. * * @see ThreadSafe */ @Documented @Target(ElementType.TYPE) @Retention(RetentionPolicy.CLASS) // The original version used RUNTIME @SdkProtectedApi public @interface NotThreadSafe { }
1,822
0
Create_ds/aws-sdk-java-v2/core/annotations/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/annotations/src/main/java/software/amazon/awssdk/annotations/SdkInternalApi.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.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Target; /** * Marker interface for 'internal' APIs that should not be used outside the same module. Breaking * changes can and will be introduced to elements marked as {@link SdkInternalApi}. Users of the SDK * and the generated clients themselves should not depend on any packages, types, fields, * constructors, or methods with this annotation. */ @Target({ElementType.PACKAGE, ElementType.TYPE, ElementType.FIELD, ElementType.CONSTRUCTOR, ElementType.METHOD}) @SdkProtectedApi public @interface SdkInternalApi { }
1,823
0
Create_ds/aws-sdk-java-v2/core/annotations/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/annotations/src/main/java/software/amazon/awssdk/annotations/Generated.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.annotations; import static java.lang.annotation.ElementType.ANNOTATION_TYPE; import static java.lang.annotation.ElementType.CONSTRUCTOR; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.LOCAL_VARIABLE; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PACKAGE; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.SOURCE; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Marker interface for generated source codes. Generated source codes should not be edited directly. */ @Documented @Retention(SOURCE) @Target({PACKAGE, TYPE, ANNOTATION_TYPE, METHOD, CONSTRUCTOR, FIELD, LOCAL_VARIABLE, PARAMETER}) @SdkProtectedApi public @interface Generated { /** * The value element MUST have the name of the code generator. * The recommended convention is to use the fully qualified name of the * code generator. For example: com.acme.generator.CodeGen. */ String[] value(); /** * Date when the source was generated. */ String date() default ""; /** * A place holder for any comments that the code generator may want to * include in the generated code. */ String comments() default ""; }
1,824
0
Create_ds/aws-sdk-java-v2/core/annotations/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/annotations/src/main/java/software/amazon/awssdk/annotations/ReviewBeforeRelease.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.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Target; /** * An annotation applied during SDK 2.0 developer preview. This makes note of something we know will change before GA or are * unsure about. By applying this annotation and making sure all instances of it are removed before GA, we will make sure not to * miss anything we intended to review. */ @Target({ElementType.PACKAGE, ElementType.TYPE, ElementType.FIELD, ElementType.CONSTRUCTOR, ElementType.METHOD}) @SdkProtectedApi public @interface ReviewBeforeRelease { /** * An explanation of why we should review this before general availability. Will it definitely change? Are we just testing * something? */ String value(); }
1,825
0
Create_ds/aws-sdk-java-v2/core/annotations/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/annotations/src/main/java/software/amazon/awssdk/annotations/NotNull.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.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * The annotated element must not be null. Accepts any type. * <p> * This is useful to tell linting and testing tools that a particular value will never be null. It's not meant to be used on * public interfaces as something that customers should rely on. */ @Documented @Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER}) @Retention(RetentionPolicy.CLASS) @SdkProtectedApi public @interface NotNull { }
1,826
0
Create_ds/aws-sdk-java-v2/core/annotations/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/annotations/src/main/java/software/amazon/awssdk/annotations/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. */ /** * AWS Java SDK annotations. */ package software.amazon.awssdk.annotations;
1,827
0
Create_ds/aws-sdk-java-v2/core/annotations/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/annotations/src/main/java/software/amazon/awssdk/annotations/ToBuilderIgnoreField.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.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Used to suppress certain fields from being considered in the spot-bugs rule for toBuilder(). This annotation must be * attached to the toBuilder() method to function. */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.CLASS) @SdkProtectedApi public @interface ToBuilderIgnoreField { /** * Specify which fields to ignore in the to-builder spotbugs rule. */ String[] value(); }
1,828
0
Create_ds/aws-sdk-java-v2/core/annotations/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/annotations/src/main/java/software/amazon/awssdk/annotations/SdkPublicApi.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.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Target; /** * Marker interface for 'public' APIs. */ @Target({ElementType.PACKAGE, ElementType.TYPE, ElementType.FIELD, ElementType.CONSTRUCTOR, ElementType.METHOD}) @SdkProtectedApi public @interface SdkPublicApi { }
1,829
0
Create_ds/aws-sdk-java-v2/core/checksums/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/checksums/src/test/java/software/amazon/awssdk/checksums/DefaultChecksumAlgorithmTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.checksums; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class DefaultChecksumAlgorithmTest { @Test public void hasCRC32C() { assertEquals("CRC32C", DefaultChecksumAlgorithm.CRC32C.algorithmId()); } @Test public void hasCRC32() { assertEquals("CRC32", DefaultChecksumAlgorithm.CRC32.algorithmId()); } @Test public void hasMD5() { assertEquals("MD5", DefaultChecksumAlgorithm.MD5.algorithmId()); } @Test public void hasSHA256() { assertEquals("SHA256", DefaultChecksumAlgorithm.SHA256.algorithmId()); } @Test public void hasSHA1() { assertEquals("SHA1", DefaultChecksumAlgorithm.SHA1.algorithmId()); } }
1,830
0
Create_ds/aws-sdk-java-v2/core/checksums/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/checksums/src/main/java/software/amazon/awssdk/checksums/DefaultChecksumAlgorithm.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.checksums; import java.util.concurrent.ConcurrentHashMap; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.checksums.spi.ChecksumAlgorithm; /** * An enumeration of supported checksum algorithms. */ @SdkProtectedApi public final class DefaultChecksumAlgorithm { public static final ChecksumAlgorithm CRC32C = of("CRC32C"); public static final ChecksumAlgorithm CRC32 = of("CRC32"); public static final ChecksumAlgorithm MD5 = of("MD5"); public static final ChecksumAlgorithm SHA256 = of("SHA256"); public static final ChecksumAlgorithm SHA1 = of("SHA1"); private DefaultChecksumAlgorithm() { } private static ChecksumAlgorithm of(String name) { return ChecksumAlgorithmsCache.put(name); } private static final class ChecksumAlgorithmsCache { private static final ConcurrentHashMap<String, ChecksumAlgorithm> VALUES = new ConcurrentHashMap<>(); private static ChecksumAlgorithm put(String value) { return VALUES.computeIfAbsent(value, v -> () -> v); } } }
1,831
0
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/test/java/software/amazon/awssdk/http/auth/spi
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/test/java/software/amazon/awssdk/http/auth/spi/scheme/AuthSchemeOptionTest.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.http.auth.spi.scheme; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; import software.amazon.awssdk.http.auth.spi.signer.SignerProperty; import software.amazon.awssdk.identity.spi.IdentityProperty; class AuthSchemeOptionTest { private static final IdentityProperty<String> IDENTITY_PROPERTY_1 = IdentityProperty.create(AuthSchemeOptionTest.class, "identityKey1"); private static final SignerProperty<String> SIGNER_PROPERTY_1 = SignerProperty.create(AuthSchemeOptionTest.class, "signingKey1"); private static final IdentityProperty<String> IDENTITY_PROPERTY_2 = IdentityProperty.create(AuthSchemeOptionTest.class, "identityKey2"); private static final SignerProperty<String> SIGNER_PROPERTY_2 = SignerProperty.create(AuthSchemeOptionTest.class, "signingKey2"); @Test public void emptyBuilder_isNotSuccessful() { assertThrows(NullPointerException.class, () -> AuthSchemeOption.builder().build()); } @Test public void build_withSchemeId_isSuccessful() { AuthSchemeOption authSchemeOption = AuthSchemeOption.builder().schemeId("my.api#myAuth").build(); assertEquals("my.api#myAuth", authSchemeOption.schemeId()); } @Test public void putProperty_sameProperty_isReplaced() { AuthSchemeOption authSchemeOption = AuthSchemeOption.builder() .schemeId("my.api#myAuth") .putIdentityProperty(IDENTITY_PROPERTY_1, "identity-value1") .putIdentityProperty(IDENTITY_PROPERTY_1, "identity-value2") .putSignerProperty(SIGNER_PROPERTY_1, "signing-value1") .putSignerProperty(SIGNER_PROPERTY_1, "signing-value2") .build(); assertEquals("identity-value2", authSchemeOption.identityProperty(IDENTITY_PROPERTY_1)); assertEquals("signing-value2", authSchemeOption.signerProperty(SIGNER_PROPERTY_1)); } @Test public void copyBuilder_addProperty_retains() { AuthSchemeOption authSchemeOption = AuthSchemeOption.builder() .schemeId("my.api#myAuth") .putIdentityProperty(IDENTITY_PROPERTY_1, "identity-value1") .putSignerProperty(SIGNER_PROPERTY_1, "signing-value1") .build(); authSchemeOption = authSchemeOption.copy(builder -> builder.putIdentityProperty(IDENTITY_PROPERTY_2, "identity2-value1") .putSignerProperty(SIGNER_PROPERTY_2, "signing2-value1")); assertEquals("identity-value1", authSchemeOption.identityProperty(IDENTITY_PROPERTY_1)); assertEquals("identity2-value1", authSchemeOption.identityProperty(IDENTITY_PROPERTY_2)); assertEquals("signing-value1", authSchemeOption.signerProperty(SIGNER_PROPERTY_1)); assertEquals("signing2-value1", authSchemeOption.signerProperty(SIGNER_PROPERTY_2)); } @Test public void copyBuilder_updateProperty_updates() { AuthSchemeOption authSchemeOption = AuthSchemeOption.builder() .schemeId("my.api#myAuth") .putIdentityProperty(IDENTITY_PROPERTY_1, "identity-value1") .putSignerProperty(SIGNER_PROPERTY_1, "signing-value1") .build(); authSchemeOption = authSchemeOption.copy(builder -> builder.putIdentityProperty(IDENTITY_PROPERTY_1, "identity-value2") .putSignerProperty(SIGNER_PROPERTY_1, "signing-value2")); assertEquals("identity-value2", authSchemeOption.identityProperty(IDENTITY_PROPERTY_1)); assertEquals("signing-value2", authSchemeOption.signerProperty(SIGNER_PROPERTY_1)); } }
1,832
0
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/test/java/software/amazon/awssdk/http/auth/spi
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/test/java/software/amazon/awssdk/http/auth/spi/signer/SignedRequestTest.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.http.auth.spi.signer; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.mock; import org.junit.jupiter.api.Test; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.utils.StringInputStream; public class SignedRequestTest { @Test public void createSignedRequest_missingRequest_throwsException() { assertThatThrownBy(() -> SignedRequest.builder().build()) .isInstanceOf(NullPointerException.class) .hasMessageContaining("request must not be null"); } @Test public void createSignedRequest_minimalBuild_works() { SdkHttpRequest request = mock(SdkHttpRequest.class); SignedRequest signedRequest = SignedRequest.builder() .request(request) .build(); assertNotNull(signedRequest); assertThat(signedRequest.request()).isEqualTo(request); } @Test public void createSignedRequest_maximalBuild_works() { SdkHttpRequest request = mock(SdkHttpRequest.class); SignedRequest signedRequest = SignedRequest.builder() .request(request) .payload(() -> new StringInputStream("test")) .build(); assertNotNull(signedRequest); assertThat(signedRequest.request()).isEqualTo(request); assertThat(signedRequest.payload()).isPresent(); } @Test public void createSignedRequest_toBuilder_works() { SdkHttpRequest request = mock(SdkHttpRequest.class); SignedRequest signedRequest = SignedRequest.builder() .request(request) .payload(() -> new StringInputStream("test")) .build(); SignedRequest copy = signedRequest.toBuilder().build(); assertNotNull(copy); assertThat(copy.request()).isEqualTo(request); assertThat(copy.payload()).isPresent(); } @Test public void createSignedRequest_copyNoChange_works() { SdkHttpRequest request = mock(SdkHttpRequest.class); SignedRequest signedRequest = SignedRequest.builder() .request(request) .payload(() -> new StringInputStream("test")) .build(); SignedRequest copy = signedRequest.copy(r -> {}); assertNotNull(copy); assertThat(copy.request()).isEqualTo(request); assertThat(copy.payload()).isPresent(); } @Test public void createSignedRequest_copyWithChange_works() { SdkHttpRequest firstRequest = mock(SdkHttpRequest.class); SdkHttpRequest secondRequest = mock(SdkHttpRequest.class); SignedRequest signedRequest = SignedRequest.builder() .request(firstRequest) .payload(() -> new StringInputStream("test")) .build(); SignedRequest copy = signedRequest.copy(r -> r.request(secondRequest)); assertNotNull(copy); assertThat(copy.request()).isEqualTo(secondRequest); assertThat(copy.payload()).isPresent(); } }
1,833
0
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/test/java/software/amazon/awssdk/http/auth/spi
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/test/java/software/amazon/awssdk/http/auth/spi/signer/HttpSignerTest.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.http.auth.spi.signer; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.mock; import java.nio.ByteBuffer; import java.util.concurrent.CompletableFuture; import org.junit.jupiter.api.Test; import org.reactivestreams.Publisher; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.identity.spi.TokenIdentity; public class HttpSignerTest { private static final SignerProperty<String> KEY = SignerProperty.create(HttpSignerTest.class, "key"); private static final String VALUE = "value"; private static final TokenIdentity IDENTITY = TokenIdentity.create("token"); final HttpSigner<TokenIdentity> signer = new TestSigner(); @Test public void sign_usingConsumerBuilder_works() { SignedRequest signedRequest = signer.sign(r -> r.request(mock(SdkHttpRequest.class)) .identity(IDENTITY) .putProperty(KEY, VALUE)); assertNotNull(signedRequest); } @Test public void sign_usingRequest_works() { SignedRequest signedRequest = signer.sign(SignRequest.builder(IDENTITY) .request(mock(SdkHttpRequest.class)) .identity(IDENTITY) // Note, this is doable .putProperty(KEY, VALUE) .build()); assertNotNull(signedRequest); } @Test public void signAsync_usingConsumerBuilder_works() { Publisher<ByteBuffer> payload = subscriber -> {}; AsyncSignedRequest signedRequest = signer.signAsync( r -> r.request(mock(SdkHttpRequest.class)) .payload(payload) .identity(IDENTITY) .putProperty(KEY, VALUE) ).join(); assertNotNull(signedRequest); } @Test public void signAsync_usingRequest_works() { Publisher<ByteBuffer> payload = subscriber -> {}; CompletableFuture<AsyncSignedRequest> signedRequest = signer.signAsync(AsyncSignRequest.builder(IDENTITY) .request(mock(SdkHttpRequest.class)) .payload(payload) .identity(IDENTITY) // Note, this is doable .putProperty(KEY, VALUE) .build()); assertNotNull(signedRequest); } /** * NoOp Signer that asserts that the input created via builder or Consumer builder pattern are set up correctly. * This is similar to what a bearerTokenSigner would look like - which would insert the identity in a Header. */ private static class TestSigner implements HttpSigner<TokenIdentity> { @Override public SignedRequest sign(SignRequest<? extends TokenIdentity> request) { assertEquals(VALUE, request.property(KEY)); assertEquals(IDENTITY, request.identity()); return SignedRequest.builder() .request(addTokenHeader(request)) .payload(request.payload().orElse(null)) .build(); } @Override public CompletableFuture<AsyncSignedRequest> signAsync(AsyncSignRequest<? extends TokenIdentity> request) { assertEquals(VALUE, request.property(KEY)); assertEquals(IDENTITY, request.identity()); return CompletableFuture.completedFuture( AsyncSignedRequest.builder() .request(addTokenHeader(request)) .payload(request.payload().orElse(null)) .build() ); } private SdkHttpRequest addTokenHeader(BaseSignRequest<?, ? extends TokenIdentity> input) { // return input.request().copy(b -> b.putHeader("Token-Header", input.identity().token())); return input.request(); } } }
1,834
0
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/test/java/software/amazon/awssdk/http/auth/spi
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/test/java/software/amazon/awssdk/http/auth/spi/signer/SignerPropertyTest.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.http.auth.spi.signer; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.UUID; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; public class SignerPropertyTest { @Test public void equalsHashcode() { EqualsVerifier.forClass(SignerProperty.class) .withNonnullFields("namespace", "name") .verify(); } @Test public void namesMustBeUnique() { String propertyName = UUID.randomUUID().toString(); SignerProperty.create(getClass(), propertyName); assertThatThrownBy(() -> SignerProperty.create(getClass(), propertyName)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining(getClass().getName()) .hasMessageContaining(propertyName); } }
1,835
0
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/test/java/software/amazon/awssdk/http/auth/spi
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/test/java/software/amazon/awssdk/http/auth/spi/signer/AsyncSignedRequestTest.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.http.auth.spi.signer; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.mock; import org.junit.jupiter.api.Test; import software.amazon.awssdk.http.SdkHttpRequest; public class AsyncSignedRequestTest { @Test public void createSignedRequest_missingRequest_throwsException() { assertThatThrownBy(() -> AsyncSignedRequest.builder().build()) .isInstanceOf(NullPointerException.class) .hasMessageContaining("request must not be null"); } @Test public void createSignedRequest_minimalBuild_works() { SdkHttpRequest request = mock(SdkHttpRequest.class); AsyncSignedRequest signedRequest = AsyncSignedRequest.builder() .request(request) .build(); assertNotNull(signedRequest); assertThat(signedRequest.request()).isEqualTo(request); } @Test public void createSignedRequest_maximalBuild_works() { SdkHttpRequest request = mock(SdkHttpRequest.class); AsyncSignedRequest signedRequest = AsyncSignedRequest.builder() .request(request) .payload(subscriber -> {}) .build(); assertNotNull(signedRequest); assertThat(signedRequest.request()).isEqualTo(request); assertThat(signedRequest.payload()).isPresent(); } @Test public void createSignedRequest_toBuilder_works() { SdkHttpRequest request = mock(SdkHttpRequest.class); AsyncSignedRequest signedRequest = AsyncSignedRequest.builder() .request(request) .payload(subscriber -> {}) .build(); AsyncSignedRequest.Builder builder = signedRequest.toBuilder(); AsyncSignedRequest copy = builder.build(); assertNotNull(copy); assertThat(copy.request()).isEqualTo(request); assertThat(copy.payload()).isPresent(); } @Test public void createSignedRequest_copyNoChange_works() { SdkHttpRequest request = mock(SdkHttpRequest.class); AsyncSignedRequest signedRequest = AsyncSignedRequest.builder() .request(request) .payload(subscriber -> {}) .build(); AsyncSignedRequest copy = signedRequest.copy(r -> {}); assertNotNull(copy); assertThat(copy.request()).isEqualTo(request); assertThat(copy.payload()).isPresent(); } @Test public void createSignedRequest_copyWithChange_works() { SdkHttpRequest firstRequest = mock(SdkHttpRequest.class); SdkHttpRequest secondRequest = mock(SdkHttpRequest.class); AsyncSignedRequest signedRequest = AsyncSignedRequest.builder() .request(firstRequest) .payload(subscriber -> {}) .build(); AsyncSignedRequest copy = signedRequest.copy(r -> r.request(secondRequest)); assertNotNull(copy); assertThat(copy.request()).isEqualTo(secondRequest); assertThat(copy.payload()).isPresent(); } }
1,836
0
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/main/java/software/amazon/awssdk/http/auth/spi
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/main/java/software/amazon/awssdk/http/auth/spi/scheme/AuthSchemeOption.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.http.auth.spi.scheme; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.http.auth.spi.internal.scheme.DefaultAuthSchemeOption; import software.amazon.awssdk.http.auth.spi.signer.SignerProperty; import software.amazon.awssdk.identity.spi.IdentityProperty; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * An authentication scheme option, composed of the scheme ID and properties for use when resolving the identity and signing * the request. * <p> * This is used in the output from the auth scheme resolver. The resolver returns a list of these, in the order the auth scheme * resolver wishes to use them. * * @see AuthScheme */ @SdkPublicApi public interface AuthSchemeOption extends ToCopyableBuilder<AuthSchemeOption.Builder, AuthSchemeOption> { /** * Get a new builder for creating a {@link AuthSchemeOption}. */ static Builder builder() { return DefaultAuthSchemeOption.builder(); } /** * Retrieve the scheme ID, a unique identifier for the authentication scheme (aws.auth#sigv4, smithy.api#httpBearerAuth). */ String schemeId(); /** * Retrieve the value of an {@link IdentityProperty}. * @param property The IdentityProperty to retrieve the value of. * @param <T> The type of the IdentityProperty. */ <T> T identityProperty(IdentityProperty<T> property); /** * Retrieve the value of an {@link SignerProperty}. * @param property The SignerProperty to retrieve the value of. * @param <T> The type of the SignerProperty. */ <T> T signerProperty(SignerProperty<T> property); /** * A method to operate on all {@link IdentityProperty} values of this AuthSchemeOption. * @param consumer The method to apply to each IdentityProperty. */ void forEachIdentityProperty(IdentityPropertyConsumer consumer); /** * A method to operate on all {@link SignerProperty} values of this AuthSchemeOption. * @param consumer The method to apply to each SignerProperty. */ void forEachSignerProperty(SignerPropertyConsumer consumer); /** * Interface for operating on an {@link IdentityProperty} value. */ @FunctionalInterface interface IdentityPropertyConsumer { /** * A method to operate on an {@link IdentityProperty} and it's value. * @param propertyKey The IdentityProperty. * @param propertyValue The value of the IdentityProperty. * @param <T> The type of the IdentityProperty. */ <T> void accept(IdentityProperty<T> propertyKey, T propertyValue); } /** * Interface for operating on an {@link SignerProperty} value. */ @FunctionalInterface interface SignerPropertyConsumer { /** * A method to operate on a {@link SignerProperty} and it's value. * @param propertyKey The SignerProperty. * @param propertyValue The value of the SignerProperty. * @param <T> The type of the SignerProperty. */ <T> void accept(SignerProperty<T> propertyKey, T propertyValue); } /** * A builder for a {@link AuthSchemeOption}. */ interface Builder extends CopyableBuilder<Builder, AuthSchemeOption> { /** * Set the scheme ID. */ Builder schemeId(String schemeId); /** * Update or add the provided property value. */ <T> Builder putIdentityProperty(IdentityProperty<T> key, T value); /** * Add the provided property value if the property does not already exist. */ <T> Builder putIdentityPropertyIfAbsent(IdentityProperty<T> key, T value); /** * Update or add the provided property value. */ <T> Builder putSignerProperty(SignerProperty<T> key, T value); /** * Add the provided property value if the property does not already exist. */ <T> Builder putSignerPropertyIfAbsent(SignerProperty<T> key, T value); } }
1,837
0
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/main/java/software/amazon/awssdk/http/auth/spi
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/main/java/software/amazon/awssdk/http/auth/spi/scheme/AuthSchemeProvider.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.http.auth.spi.scheme; import software.amazon.awssdk.annotations.SdkPublicApi; /** * A marker interface for an auth scheme provider. An auth scheme provider takes as input a set of service-specific parameters, * and resolves a list of {@link AuthSchemeOption} based on the given parameters. */ @SdkPublicApi public interface AuthSchemeProvider { }
1,838
0
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/main/java/software/amazon/awssdk/http/auth/spi
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/main/java/software/amazon/awssdk/http/auth/spi/scheme/AuthScheme.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.http.auth.spi.scheme; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.http.auth.spi.signer.HttpSigner; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.Identity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.identity.spi.IdentityProviders; import software.amazon.awssdk.identity.spi.TokenIdentity; /** * An authentication scheme, composed of: * <ol> * <li>A scheme ID - A unique identifier for the authentication scheme.</li> * <li>An identity provider - An API that can be queried to acquire the customer's identity.</li> * <li>A signer - An API that can be used to sign HTTP requests.</li> * </ol> * * See example auth schemes defined <a href="https://smithy.io/2.0/spec/authentication-traits.html">here</a>. * * @param <T> The type of the {@link Identity} used by this authentication scheme. * @see IdentityProvider * @see HttpSigner */ @SdkPublicApi public interface AuthScheme<T extends Identity> { /** * Retrieve the scheme ID, a unique identifier for the authentication scheme. */ String schemeId(); /** * Retrieve the identity provider associated with this authentication scheme. The identity generated by this provider is * guaranteed to be supported by the signer in this authentication scheme. * <p> * For example, if the scheme ID is aws.auth#sigv4, the provider returns an {@link AwsCredentialsIdentity}, if the scheme ID * is httpBearerAuth, the provider returns a {@link TokenIdentity}. * <p> * Note, the returned identity provider may differ from the type of identity provider retrieved from the provided * {@link IdentityProviders}. */ IdentityProvider<T> identityProvider(IdentityProviders providers); /** * Retrieve the signer associated with this authentication scheme. This signer is guaranteed to support the identity generated * by the identity provider in this authentication scheme. */ HttpSigner<T> signer(); }
1,839
0
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/main/java/software/amazon/awssdk/http/auth/spi
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/main/java/software/amazon/awssdk/http/auth/spi/signer/HttpSigner.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.http.auth.spi.signer; import java.time.Clock; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.http.auth.spi.internal.signer.DefaultAsyncSignRequest; import software.amazon.awssdk.http.auth.spi.internal.signer.DefaultSignRequest; import software.amazon.awssdk.identity.spi.Identity; /** * Interface for the process of modifying a request destined for a service so that the service can authenticate the SDK * customer’s identity. * * @param <IdentityT> The type of the identity. */ @SdkPublicApi public interface HttpSigner<IdentityT extends Identity> { /** * A {@link Clock} to be used to derive the signing time. This property defaults to the system clock. * * <p>Note, signing time may not be relevant to some signers. */ SignerProperty<Clock> SIGNING_CLOCK = SignerProperty.create(HttpSigner.class, "SigningClock"); /** * Method that takes in inputs to sign a request with sync payload and returns a signed version of the request. * * @param request The inputs to sign a request. * @return A signed version of the request. */ SignedRequest sign(SignRequest<? extends IdentityT> request); /** * Method that takes in inputs to sign a request with sync payload and returns a signed version of the request. * <p> * Similar to {@link #sign(SignRequest)}, but takes a lambda to configure a new {@link SignRequest.Builder}. * This removes the need to call {@link SignRequest#builder(IdentityT)}} and * {@link SignRequest.Builder#build()}. * * @param consumer A {@link Consumer} to which an empty {@link SignRequest.Builder} will be given. * @return A signed version of the request. */ default SignedRequest sign(Consumer<SignRequest.Builder<IdentityT>> consumer) { return sign(DefaultSignRequest.<IdentityT>builder().applyMutation(consumer).build()); } /** * Method that takes in inputs to sign a request with async payload and returns a future containing the signed version of the * request. * * @param request The inputs to sign a request. * @return A future containing the signed version of the request. */ CompletableFuture<AsyncSignedRequest> signAsync(AsyncSignRequest<? extends IdentityT> request); /** * Method that takes in inputs to sign a request with async payload and returns a future containing the signed version of the * request. * <p> * Similar to {@link #signAsync(AsyncSignRequest)}, but takes a lambda to configure a new * {@link AsyncSignRequest.Builder}. This removes the need to call {@link AsyncSignRequest#builder(IdentityT)}} and * {@link AsyncSignRequest.Builder#build()}. * * @param consumer A {@link Consumer} to which an empty {@link BaseSignRequest.Builder} will be given. * @return A future containing the signed version of the request. */ default CompletableFuture<AsyncSignedRequest> signAsync(Consumer<AsyncSignRequest.Builder<IdentityT>> consumer) { return signAsync(DefaultAsyncSignRequest.<IdentityT>builder().applyMutation(consumer).build()); } }
1,840
0
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/main/java/software/amazon/awssdk/http/auth/spi
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/main/java/software/amazon/awssdk/http/auth/spi/signer/SignedRequest.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.http.auth.spi.signer; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.http.ContentStreamProvider; import software.amazon.awssdk.http.auth.spi.internal.signer.DefaultSignedRequest; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * Represents a request with sync payload that has been signed by {@link HttpSigner}. */ @SdkPublicApi @Immutable @ThreadSafe public interface SignedRequest extends BaseSignedRequest<ContentStreamProvider>, ToCopyableBuilder<SignedRequest.Builder, SignedRequest> { /** * Get a new builder for creating a {@link SignedRequest}. */ static Builder builder() { return DefaultSignedRequest.builder(); } /** * A builder for a {@link SignedRequest}. */ interface Builder extends BaseSignedRequest.Builder<Builder, ContentStreamProvider>, CopyableBuilder<Builder, SignedRequest> { } }
1,841
0
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/main/java/software/amazon/awssdk/http/auth/spi
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/main/java/software/amazon/awssdk/http/auth/spi/signer/AsyncSignRequest.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.http.auth.spi.signer; import java.nio.ByteBuffer; import org.reactivestreams.Publisher; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.http.auth.spi.internal.signer.DefaultAsyncSignRequest; import software.amazon.awssdk.identity.spi.Identity; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * Input parameters to sign a request with async payload, using {@link HttpSigner}. * * @param <IdentityT> The type of the identity. */ @SdkPublicApi @Immutable @ThreadSafe public interface AsyncSignRequest<IdentityT extends Identity> extends BaseSignRequest<Publisher<ByteBuffer>, IdentityT>, ToCopyableBuilder<AsyncSignRequest.Builder<IdentityT>, AsyncSignRequest<IdentityT>> { /** * Get a new builder for creating a {@link AsyncSignRequest}. */ static <IdentityT extends Identity> Builder<IdentityT> builder(IdentityT identity) { return DefaultAsyncSignRequest.builder(identity); } /** * A builder for a {@link AsyncSignRequest}. */ interface Builder<IdentityT extends Identity> extends BaseSignRequest.Builder<Builder<IdentityT>, Publisher<ByteBuffer>, IdentityT>, CopyableBuilder<Builder<IdentityT>, AsyncSignRequest<IdentityT>> { } }
1,842
0
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/main/java/software/amazon/awssdk/http/auth/spi
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/main/java/software/amazon/awssdk/http/auth/spi/signer/SignRequest.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.http.auth.spi.signer; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.http.ContentStreamProvider; import software.amazon.awssdk.http.auth.spi.internal.signer.DefaultSignRequest; import software.amazon.awssdk.identity.spi.Identity; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * Input parameters to sign a request with sync payload, using {@link HttpSigner}. * * @param <IdentityT> The type of the identity. */ @SdkPublicApi @Immutable @ThreadSafe public interface SignRequest<IdentityT extends Identity> extends BaseSignRequest<ContentStreamProvider, IdentityT>, ToCopyableBuilder<SignRequest.Builder<IdentityT>, SignRequest<IdentityT>> { /** * Get a new builder for creating a {@link SignRequest}. */ static <IdentityT extends Identity> Builder<IdentityT> builder(IdentityT identity) { return DefaultSignRequest.builder(identity); } /** * A builder for a {@link SignRequest}. */ interface Builder<IdentityT extends Identity> extends BaseSignRequest.Builder<Builder<IdentityT>, ContentStreamProvider, IdentityT>, CopyableBuilder<Builder<IdentityT>, SignRequest<IdentityT>> { } }
1,843
0
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/main/java/software/amazon/awssdk/http/auth/spi
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/main/java/software/amazon/awssdk/http/auth/spi/signer/BaseSignRequest.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.http.auth.spi.signer; import java.util.Optional; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.identity.spi.Identity; import software.amazon.awssdk.utils.Validate; /** * Base interface to represent input parameters to sign a request using {@link HttpSigner}, independent of payload type. See * specific sub-interfaces {@link SignRequest} for sync payload and {@link AsyncSignRequest} for async payload. * * @param <PayloadT> The type of payload of the request. * @param <IdentityT> The type of the identity. */ @SdkPublicApi @Immutable @ThreadSafe public interface BaseSignRequest<PayloadT, IdentityT extends Identity> { /** * Returns the HTTP request object, without the request body payload. */ SdkHttpRequest request(); /** * Returns the body payload of the request. A payload is optional. By default, the payload will be empty. */ Optional<PayloadT> payload(); /** * Returns the identity. */ IdentityT identity(); /** * Returns the value of a property that the {@link HttpSigner} can use during signing. */ <T> T property(SignerProperty<T> property); /** * Ensure that the {@link SignerProperty} is present in the {@link BaseSignRequest}. * <p> * The value, {@link T}, is return when present, and an exception is thrown otherwise. */ default <T> boolean hasProperty(SignerProperty<T> property) { return property(property) != null; } /** * Ensure that the {@link SignerProperty} is present in the {@link BaseSignRequest}. * <p> * The value, {@link T}, is return when present, and an exception is thrown otherwise. */ default <T> T requireProperty(SignerProperty<T> property) { return Validate.notNull(property(property), property.toString() + " must not be null!"); } /** * Ensure that the {@link SignerProperty} is present in the {@link BaseSignRequest}. * <p> * The value, {@link T}, is return when present, and the default is returned otherwise. */ default <T> T requireProperty(SignerProperty<T> property, T defaultValue) { return Validate.getOrDefault(property(property), () -> defaultValue); } /** * A builder for a {@link BaseSignRequest}. */ interface Builder<B extends Builder<B, PayloadT, IdentityT>, PayloadT, IdentityT extends Identity> { /** * Set the HTTP request object, without the request body payload. */ B request(SdkHttpRequest request); /** * Set the body payload of the request. A payload is optional. By default, the payload will be empty. */ B payload(PayloadT payload); /** * Set the identity of the request. */ B identity(IdentityT identity); /** * Set a property that the {@link HttpSigner} can use during signing. */ <T> B putProperty(SignerProperty<T> key, T value); } }
1,844
0
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/main/java/software/amazon/awssdk/http/auth/spi
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/main/java/software/amazon/awssdk/http/auth/spi/signer/AsyncSignedRequest.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.http.auth.spi.signer; import java.nio.ByteBuffer; import org.reactivestreams.Publisher; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.http.auth.spi.internal.signer.DefaultAsyncSignedRequest; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * Represents a request with async payload that has been signed by {@link HttpSigner}. */ @SdkPublicApi @Immutable @ThreadSafe public interface AsyncSignedRequest extends BaseSignedRequest<Publisher<ByteBuffer>>, ToCopyableBuilder<AsyncSignedRequest.Builder, AsyncSignedRequest> { /** * Get a new builder for creating a {@link AsyncSignedRequest}. */ static Builder builder() { return DefaultAsyncSignedRequest.builder(); } /** * A builder for a {@link AsyncSignedRequest}. */ interface Builder extends BaseSignedRequest.Builder<Builder, Publisher<ByteBuffer>>, CopyableBuilder<AsyncSignedRequest.Builder, AsyncSignedRequest> { } }
1,845
0
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/main/java/software/amazon/awssdk/http/auth/spi
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/main/java/software/amazon/awssdk/http/auth/spi/signer/SignerProperty.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.http.auth.spi.signer; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.utils.Pair; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.Validate; /** * A strongly-typed property for input to an {@link HttpSigner}. * @param <T> The type of the property. */ @SdkPublicApi @Immutable @ThreadSafe public final class SignerProperty<T> { private static final ConcurrentMap<Pair<String, String>, SignerProperty<?>> NAME_HISTORY = new ConcurrentHashMap<>(); private final String namespace; private final String name; private SignerProperty(String namespace, String name) { Validate.paramNotBlank(namespace, "namespace"); Validate.paramNotBlank(name, "name"); this.namespace = namespace; this.name = name; ensureUnique(); } /** * Create a property. * * @param <T> the type of the property. * @param namespace the class *where* the property is being defined * @param name the name for the property * @throws IllegalArgumentException if a property with this namespace and name already exist */ public static <T> SignerProperty<T> create(Class<?> namespace, String name) { return new SignerProperty<>(namespace.getName(), name); } private void ensureUnique() { SignerProperty<?> prev = NAME_HISTORY.putIfAbsent(Pair.of(namespace, name), this); Validate.isTrue(prev == null, "No duplicate SignerProperty names allowed but both SignerProperties %s and %s have the same namespace " + "(%s) and name (%s). SignerProperty should be referenced from a shared static constant to protect " + "against erroneous or unexpected collisions.", Integer.toHexString(System.identityHashCode(prev)), Integer.toHexString(System.identityHashCode(this)), namespace, name); } @Override public String toString() { return ToString.builder("SignerProperty") .add("namespace", namespace) .add("name", name) .build(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SignerProperty<?> that = (SignerProperty<?>) o; return Objects.equals(namespace, that.namespace) && Objects.equals(name, that.name); } @Override public int hashCode() { int hashCode = 1; hashCode = 31 * hashCode + Objects.hashCode(namespace); hashCode = 31 * hashCode + Objects.hashCode(name); return hashCode; } }
1,846
0
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/main/java/software/amazon/awssdk/http/auth/spi
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/main/java/software/amazon/awssdk/http/auth/spi/signer/BaseSignedRequest.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.http.auth.spi.signer; import java.util.Optional; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.http.SdkHttpRequest; /** /** * Base interface to a request that has been signed by {@link HttpSigner}, independent of payload type. See specific * sub-interfaces {@link SignedRequest} for sync payload and {@link AsyncSignedRequest} for async payload. * * @param <PayloadT> The type of payload of the request. */ @SdkPublicApi @Immutable @ThreadSafe public interface BaseSignedRequest<PayloadT> { /** * Returns the HTTP request object, without the request body payload. */ SdkHttpRequest request(); /** * Returns the body payload of the request. A payload is optional. By default, the payload will be empty. */ Optional<PayloadT> payload(); /** * A builder for a {@link BaseSignedRequest}. */ interface Builder<B extends Builder<B, PayloadT>, PayloadT> { /** * Set the HTTP request object, without the request body payload. */ B request(SdkHttpRequest request); /** * Set the body payload of the request. A payload is optional. By default, the payload will be empty. */ B payload(PayloadT payload); } }
1,847
0
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/main/java/software/amazon/awssdk/http/auth/spi/internal
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/main/java/software/amazon/awssdk/http/auth/spi/internal/scheme/DefaultAuthSchemeOption.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.http.auth.spi.internal.scheme; import java.util.HashMap; import java.util.Map; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeOption; import software.amazon.awssdk.http.auth.spi.signer.SignerProperty; import software.amazon.awssdk.identity.spi.IdentityProperty; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.Validate; @SdkInternalApi @Immutable public final class DefaultAuthSchemeOption implements AuthSchemeOption { private final String schemeId; private final Map<IdentityProperty<?>, Object> identityProperties; private final Map<SignerProperty<?>, Object> signerProperties; DefaultAuthSchemeOption(BuilderImpl builder) { this.schemeId = Validate.paramNotBlank(builder.schemeId, "schemeId"); this.identityProperties = new HashMap<>(builder.identityProperties); this.signerProperties = new HashMap<>(builder.signerProperties); } public static Builder builder() { return new BuilderImpl(); } @Override public String schemeId() { return schemeId; } @SuppressWarnings("unchecked") // Safe because of the implementation of putIdentityProperty @Override public <T> T identityProperty(IdentityProperty<T> property) { return (T) identityProperties.get(property); } @SuppressWarnings("unchecked") // Safe because of the implementation of putSignerProperty @Override public <T> T signerProperty(SignerProperty<T> property) { return (T) signerProperties.get(property); } @Override public void forEachIdentityProperty(IdentityPropertyConsumer consumer) { identityProperties.keySet().forEach(property -> consumeProperty(property, consumer)); } private <T> void consumeProperty(IdentityProperty<T> property, IdentityPropertyConsumer consumer) { consumer.accept(property, this.identityProperty(property)); } @Override public void forEachSignerProperty(SignerPropertyConsumer consumer) { signerProperties.keySet().forEach(property -> consumeProperty(property, consumer)); } private <T> void consumeProperty(SignerProperty<T> property, SignerPropertyConsumer consumer) { consumer.accept(property, this.signerProperty(property)); } @Override public Builder toBuilder() { return new BuilderImpl(this); } @Override public String toString() { return ToString.builder("AuthSchemeOption") .add("schemeId", schemeId) .add("identityProperties", identityProperties) .add("signerProperties", signerProperties) .build(); } public static final class BuilderImpl implements Builder { private String schemeId; private final Map<IdentityProperty<?>, Object> identityProperties = new HashMap<>(); private final Map<SignerProperty<?>, Object> signerProperties = new HashMap<>(); private BuilderImpl() { } private BuilderImpl(DefaultAuthSchemeOption authSchemeOption) { this.schemeId = authSchemeOption.schemeId; this.identityProperties.putAll(authSchemeOption.identityProperties); this.signerProperties.putAll(authSchemeOption.signerProperties); } @Override public Builder schemeId(String schemeId) { this.schemeId = schemeId; return this; } @Override public <T> Builder putIdentityProperty(IdentityProperty<T> key, T value) { this.identityProperties.put(key, value); return this; } @Override public <T> Builder putIdentityPropertyIfAbsent(IdentityProperty<T> key, T value) { this.identityProperties.putIfAbsent(key, value); return this; } @Override public <T> Builder putSignerProperty(SignerProperty<T> key, T value) { this.signerProperties.put(key, value); return this; } @Override public <T> Builder putSignerPropertyIfAbsent(SignerProperty<T> key, T value) { this.signerProperties.putIfAbsent(key, value); return this; } @Override public AuthSchemeOption build() { return new DefaultAuthSchemeOption(this); } } }
1,848
0
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/main/java/software/amazon/awssdk/http/auth/spi/internal
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/main/java/software/amazon/awssdk/http/auth/spi/internal/signer/DefaultBaseSignedRequest.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.http.auth.spi.internal.signer; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.auth.spi.signer.BaseSignedRequest; import software.amazon.awssdk.utils.Validate; @SdkInternalApi abstract class DefaultBaseSignedRequest<PayloadT> implements BaseSignedRequest<PayloadT> { protected final SdkHttpRequest request; protected final PayloadT payload; protected DefaultBaseSignedRequest(BuilderImpl<?, PayloadT> builder) { this.request = Validate.paramNotNull(builder.request, "request"); this.payload = builder.payload; } @Override public SdkHttpRequest request() { return request; } @Override public Optional<PayloadT> payload() { return Optional.ofNullable(payload); } protected abstract static class BuilderImpl<B extends Builder<B, PayloadT>, PayloadT> implements Builder<B, PayloadT> { private SdkHttpRequest request; private PayloadT payload; protected BuilderImpl() { } @Override public B request(SdkHttpRequest request) { this.request = request; return thisBuilder(); } @Override public B payload(PayloadT payload) { this.payload = payload; return thisBuilder(); } private B thisBuilder() { return (B) this; } } }
1,849
0
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/main/java/software/amazon/awssdk/http/auth/spi/internal
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/main/java/software/amazon/awssdk/http/auth/spi/internal/signer/DefaultBaseSignRequest.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.http.auth.spi.internal.signer; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.auth.spi.signer.BaseSignRequest; import software.amazon.awssdk.http.auth.spi.signer.SignerProperty; import software.amazon.awssdk.identity.spi.Identity; import software.amazon.awssdk.utils.Validate; @SdkInternalApi abstract class DefaultBaseSignRequest<PayloadT, IdentityT extends Identity> implements BaseSignRequest<PayloadT, IdentityT> { protected final SdkHttpRequest request; protected final PayloadT payload; protected final IdentityT identity; protected final Map<SignerProperty<?>, Object> properties; protected DefaultBaseSignRequest(BuilderImpl<?, PayloadT, IdentityT> builder) { this.request = Validate.paramNotNull(builder.request, "request"); this.payload = builder.payload; this.identity = Validate.paramNotNull(builder.identity, "identity"); this.properties = Collections.unmodifiableMap(new HashMap<>(builder.properties)); } @Override public SdkHttpRequest request() { return request; } @Override public Optional<PayloadT> payload() { return Optional.ofNullable(payload); } @Override public IdentityT identity() { return identity; } @Override public <T> T property(SignerProperty<T> property) { return (T) properties.get(property); } @SdkInternalApi protected abstract static class BuilderImpl<B extends Builder<B, PayloadT, IdentityT>, PayloadT, IdentityT extends Identity> implements Builder<B, PayloadT, IdentityT> { private final Map<SignerProperty<?>, Object> properties = new HashMap<>(); private SdkHttpRequest request; private PayloadT payload; private IdentityT identity; protected BuilderImpl() { } protected BuilderImpl(IdentityT identity) { this.identity = identity; } @Override public B request(SdkHttpRequest request) { this.request = request; return thisBuilder(); } @Override public B payload(PayloadT payload) { this.payload = payload; return thisBuilder(); } @Override public B identity(IdentityT identity) { this.identity = identity; return thisBuilder(); } @Override public <T> B putProperty(SignerProperty<T> key, T value) { this.properties.put(key, value); return thisBuilder(); } protected B properties(Map<SignerProperty<?>, Object> properties) { this.properties.clear(); this.properties.putAll(properties); return thisBuilder(); } private B thisBuilder() { return (B) this; } } }
1,850
0
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/main/java/software/amazon/awssdk/http/auth/spi/internal
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/main/java/software/amazon/awssdk/http/auth/spi/internal/signer/DefaultAsyncSignRequest.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.http.auth.spi.internal.signer; import java.nio.ByteBuffer; import org.reactivestreams.Publisher; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.auth.spi.signer.AsyncSignRequest; import software.amazon.awssdk.identity.spi.Identity; import software.amazon.awssdk.utils.ToString; @SdkInternalApi public final class DefaultAsyncSignRequest<IdentityT extends Identity> extends DefaultBaseSignRequest<Publisher<ByteBuffer>, IdentityT> implements AsyncSignRequest<IdentityT> { private DefaultAsyncSignRequest(BuilderImpl<IdentityT> builder) { super(builder); } public static <IdentityT extends Identity> AsyncSignRequest.Builder<IdentityT> builder() { return new BuilderImpl<>(); } public static <IdentityT extends Identity> AsyncSignRequest.Builder<IdentityT> builder(IdentityT identity) { return new BuilderImpl<>(identity); } @Override public String toString() { return ToString.builder("AsyncSignRequest") .add("request", request) .add("identity", identity) .add("properties", properties) .build(); } @Override public AsyncSignRequest.Builder<IdentityT> toBuilder() { return new BuilderImpl<>(this); } @SdkInternalApi public static final class BuilderImpl<IdentityT extends Identity> extends DefaultBaseSignRequest.BuilderImpl<AsyncSignRequest.Builder<IdentityT>, Publisher<ByteBuffer>, IdentityT> implements AsyncSignRequest.Builder<IdentityT> { // Used to enable consumer builder pattern in HttpSigner.signAsync() private BuilderImpl() { } // Used by AsyncSignRequest#builder() where identity is passed as parameter, to avoid having to pass Class<IdentityT>. private BuilderImpl(IdentityT identity) { super(identity); } private BuilderImpl(DefaultAsyncSignRequest<IdentityT> request) { properties(request.properties); identity(request.identity); payload(request.payload); request(request.request); } @Override public AsyncSignRequest<IdentityT> build() { return new DefaultAsyncSignRequest<>(this); } } }
1,851
0
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/main/java/software/amazon/awssdk/http/auth/spi/internal
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/main/java/software/amazon/awssdk/http/auth/spi/internal/signer/DefaultAsyncSignedRequest.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.http.auth.spi.internal.signer; import java.nio.ByteBuffer; import org.reactivestreams.Publisher; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.auth.spi.signer.AsyncSignedRequest; import software.amazon.awssdk.utils.ToString; @SdkInternalApi public final class DefaultAsyncSignedRequest extends DefaultBaseSignedRequest<Publisher<ByteBuffer>> implements AsyncSignedRequest { private DefaultAsyncSignedRequest(BuilderImpl builder) { super(builder); } public static BuilderImpl builder() { return new BuilderImpl(); } @Override public String toString() { return ToString.builder("AsyncSignedRequest") .add("request", request) .build(); } @Override public AsyncSignedRequest.Builder toBuilder() { return AsyncSignedRequest.builder().request(request).payload(payload); } @SdkInternalApi public static final class BuilderImpl extends DefaultBaseSignedRequest.BuilderImpl<AsyncSignedRequest.Builder, Publisher<ByteBuffer>> implements AsyncSignedRequest.Builder { private BuilderImpl() { } @Override public AsyncSignedRequest build() { return new DefaultAsyncSignedRequest(this); } } }
1,852
0
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/main/java/software/amazon/awssdk/http/auth/spi/internal
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/main/java/software/amazon/awssdk/http/auth/spi/internal/signer/DefaultSignedRequest.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.http.auth.spi.internal.signer; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.ContentStreamProvider; import software.amazon.awssdk.http.auth.spi.signer.SignedRequest; import software.amazon.awssdk.utils.ToString; @SdkInternalApi public final class DefaultSignedRequest extends DefaultBaseSignedRequest<ContentStreamProvider> implements SignedRequest { private DefaultSignedRequest(BuilderImpl builder) { super(builder); } public static BuilderImpl builder() { return new BuilderImpl(); } @Override public String toString() { return ToString.builder("SyncSignedRequest") .add("request", request) .build(); } @Override public SignedRequest.Builder toBuilder() { return SignedRequest.builder().request(request).payload(payload); } @SdkInternalApi public static final class BuilderImpl extends DefaultBaseSignedRequest.BuilderImpl<SignedRequest.Builder, ContentStreamProvider> implements SignedRequest.Builder { private BuilderImpl() { } @Override public SignedRequest build() { return new DefaultSignedRequest(this); } } }
1,853
0
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/main/java/software/amazon/awssdk/http/auth/spi/internal
Create_ds/aws-sdk-java-v2/core/http-auth-spi/src/main/java/software/amazon/awssdk/http/auth/spi/internal/signer/DefaultSignRequest.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.http.auth.spi.internal.signer; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.ContentStreamProvider; import software.amazon.awssdk.http.auth.spi.signer.SignRequest; import software.amazon.awssdk.identity.spi.Identity; import software.amazon.awssdk.utils.ToString; @SdkInternalApi public final class DefaultSignRequest<IdentityT extends Identity> extends DefaultBaseSignRequest<ContentStreamProvider, IdentityT> implements SignRequest<IdentityT> { private DefaultSignRequest(BuilderImpl<IdentityT> builder) { super(builder); } public static <IdentityT extends Identity> SignRequest.Builder<IdentityT> builder() { return new BuilderImpl<>(); } public static <IdentityT extends Identity> SignRequest.Builder<IdentityT> builder(IdentityT identity) { return new BuilderImpl<>(identity); } @Override public String toString() { return ToString.builder("SignRequest") .add("request", request) .add("identity", identity) .add("properties", properties) .build(); } @Override public SignRequest.Builder<IdentityT> toBuilder() { return new BuilderImpl<>(this); } @SdkInternalApi public static final class BuilderImpl<IdentityT extends Identity> extends DefaultBaseSignRequest.BuilderImpl<SignRequest.Builder<IdentityT>, ContentStreamProvider, IdentityT> implements SignRequest.Builder<IdentityT> { // Used to enable consumer builder pattern in HttpSigner.sign() private BuilderImpl() { } // Used by SignRequest#builder() where identity is passed as parameter, to avoid having to pass Class<IdentityT>. private BuilderImpl(IdentityT identity) { super(identity); } private BuilderImpl(DefaultSignRequest<IdentityT> request) { properties(request.properties); identity(request.identity); payload(request.payload); request(request.request); } @Override public SignRequest<IdentityT> build() { return new DefaultSignRequest<>(this); } } }
1,854
0
Create_ds/aws-sdk-java-v2/core/http-auth/src/test/java/software/amazon/awssdk/http/auth
Create_ds/aws-sdk-java-v2/core/http-auth/src/test/java/software/amazon/awssdk/http/auth/signer/BearerHttpSignerTest.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.http.auth.signer; import static org.assertj.core.api.Assertions.assertThat; import java.io.ByteArrayInputStream; import java.net.URI; import org.junit.jupiter.api.Test; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.auth.spi.signer.AsyncSignRequest; import software.amazon.awssdk.http.auth.spi.signer.AsyncSignedRequest; import software.amazon.awssdk.http.auth.spi.signer.SignRequest; import software.amazon.awssdk.http.auth.spi.signer.SignedRequest; import software.amazon.awssdk.identity.spi.TokenIdentity; import software.amazon.awssdk.utils.async.SimplePublisher; class BearerHttpSignerTest { private static final String BEARER_AUTH_MARKER = "Bearer "; private static String createExpectedHeader(String token) { return BEARER_AUTH_MARKER + token; } private static SignRequest<? extends TokenIdentity> generateBasicRequest(String token) { return SignRequest.builder(TokenIdentity.create(token)) .request(SdkHttpRequest.builder() .method(SdkHttpMethod.POST) .putHeader("Host", "demo.us-east-1.amazonaws.com") .putHeader("x-amz-archive-description", "test test") .encodedPath("/") .uri(URI.create("http://demo.us-east-1.amazonaws.com")) .build()) .payload(() -> new ByteArrayInputStream("{\"TableName\": \"foo\"}".getBytes())) .build(); } private static AsyncSignRequest<? extends TokenIdentity> generateBasicAsyncRequest(String token) { return AsyncSignRequest.builder(TokenIdentity.create(token)) .request(SdkHttpRequest.builder() .method(SdkHttpMethod.POST) .putHeader("Host", "demo.us-east-1.amazonaws.com") .putHeader("x-amz-archive-description", "test test") .encodedPath("/") .uri(URI.create("http://demo.us-east-1.amazonaws.com")) .build()) .payload(new SimplePublisher<>()) .build(); } @Test public void whenTokenExists_requestIsSignedCorrectly() { String tokenValue = "mF_9.B5f-4.1JqM"; BearerHttpSigner tokenSigner = BearerHttpSigner.create(); SignedRequest signedRequest = tokenSigner.sign(generateBasicRequest(tokenValue)); String expectedHeader = createExpectedHeader(tokenValue); assertThat(signedRequest.request().firstMatchingHeader( "Authorization")).hasValue(expectedHeader); } @Test public void whenTokenExists_asyncRequestIsSignedCorrectly() { String tokenValue = "mF_9.B5f-4.1JqM"; BearerHttpSigner tokenSigner = BearerHttpSigner.create(); AsyncSignedRequest signedRequest = tokenSigner.signAsync(generateBasicAsyncRequest(tokenValue)).join(); String expectedHeader = createExpectedHeader(tokenValue); assertThat(signedRequest.request().firstMatchingHeader( "Authorization")).hasValue(expectedHeader); } }
1,855
0
Create_ds/aws-sdk-java-v2/core/http-auth/src/main/java/software/amazon/awssdk/http/auth
Create_ds/aws-sdk-java-v2/core/http-auth/src/main/java/software/amazon/awssdk/http/auth/scheme/NoAuthAuthScheme.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.http.auth.scheme; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.http.auth.internal.scheme.DefaultNoAuthAuthScheme; import software.amazon.awssdk.http.auth.spi.scheme.AuthScheme; import software.amazon.awssdk.http.auth.spi.signer.HttpSigner; import software.amazon.awssdk.identity.spi.Identity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.identity.spi.IdentityProviders; /** * An auth scheme that represents no authentication. */ @SdkPublicApi public interface NoAuthAuthScheme extends AuthScheme<NoAuthAuthScheme.AnonymousIdentity> { /** * The scheme ID for the no-auth auth scheme. */ String SCHEME_ID = "smithy.api#noAuth"; static NoAuthAuthScheme create() { return DefaultNoAuthAuthScheme.create(); } /** * Retrieve the {@link AnonymousIdentity} based {@link IdentityProvider} associated with this authentication scheme. */ @Override IdentityProvider<AnonymousIdentity> identityProvider(IdentityProviders providers); /** * Retrieve the {@link HttpSigner} associated with this authentication scheme. */ @Override HttpSigner<AnonymousIdentity> signer(); /** * An anonymous identity used by the no-auth auth scheme. */ interface AnonymousIdentity extends Identity { } }
1,856
0
Create_ds/aws-sdk-java-v2/core/http-auth/src/main/java/software/amazon/awssdk/http/auth
Create_ds/aws-sdk-java-v2/core/http-auth/src/main/java/software/amazon/awssdk/http/auth/scheme/BearerAuthScheme.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.http.auth.scheme; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.http.auth.internal.scheme.DefaultBearerAuthScheme; import software.amazon.awssdk.http.auth.signer.BearerHttpSigner; import software.amazon.awssdk.http.auth.spi.scheme.AuthScheme; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.identity.spi.IdentityProviders; import software.amazon.awssdk.identity.spi.TokenIdentity; /** * The <a href="https://smithy.io/2.0/spec/authentication-traits.html#httpbearerauth-trait">smithy.api#httpBearerAuth</a> auth * scheme, which uses a {@link TokenIdentity} and {@link BearerHttpSigner}. */ @SdkPublicApi public interface BearerAuthScheme extends AuthScheme<TokenIdentity> { /** * The scheme ID for this interface. */ String SCHEME_ID = "smithy.api#httpBearerAuth"; /** * Get a default implementation of a {@link BearerAuthScheme} */ static BearerAuthScheme create() { return DefaultBearerAuthScheme.create(); } /** * Retrieve the {@link TokenIdentity} based {@link IdentityProvider} associated with this authentication scheme. */ @Override IdentityProvider<TokenIdentity> identityProvider(IdentityProviders providers); /** * Retrieve the {@link BearerHttpSigner} associated with this authentication scheme. */ @Override BearerHttpSigner signer(); }
1,857
0
Create_ds/aws-sdk-java-v2/core/http-auth/src/main/java/software/amazon/awssdk/http/auth
Create_ds/aws-sdk-java-v2/core/http-auth/src/main/java/software/amazon/awssdk/http/auth/signer/BearerHttpSigner.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.http.auth.signer; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.http.auth.internal.signer.DefaultBearerHttpSigner; import software.amazon.awssdk.http.auth.spi.signer.HttpSigner; import software.amazon.awssdk.identity.spi.TokenIdentity; /** * An {@link HttpSigner} that will sign a request with a bearer-token ({@link TokenIdentity}). */ @SdkPublicApi public interface BearerHttpSigner extends HttpSigner<TokenIdentity> { /** * Get a default implementation of a {@link BearerHttpSigner} * * @return BearerHttpSigner */ static BearerHttpSigner create() { return new DefaultBearerHttpSigner(); } }
1,858
0
Create_ds/aws-sdk-java-v2/core/http-auth/src/main/java/software/amazon/awssdk/http/auth/internal
Create_ds/aws-sdk-java-v2/core/http-auth/src/main/java/software/amazon/awssdk/http/auth/internal/scheme/DefaultNoAuthAuthScheme.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.http.auth.internal.scheme; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.auth.scheme.NoAuthAuthScheme; import software.amazon.awssdk.http.auth.spi.signer.AsyncSignRequest; import software.amazon.awssdk.http.auth.spi.signer.AsyncSignedRequest; import software.amazon.awssdk.http.auth.spi.signer.HttpSigner; import software.amazon.awssdk.http.auth.spi.signer.SignRequest; import software.amazon.awssdk.http.auth.spi.signer.SignedRequest; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.identity.spi.IdentityProviders; import software.amazon.awssdk.identity.spi.ResolveIdentityRequest; /** * A default implementation of {@link NoAuthAuthScheme}. This implementation always: * * <ul> * <li>Returns an {@link IdentityProvider} that always returns the same static instance that implements the * {@link AnonymousIdentity} interface</li> * <li>Returns an {@link HttpSigner} that returns the same request given in the signing request.</li> * </ul> */ @SdkInternalApi public final class DefaultNoAuthAuthScheme implements NoAuthAuthScheme { private static final DefaultNoAuthAuthScheme DEFAULT = new DefaultNoAuthAuthScheme(); private static final IdentityProvider<AnonymousIdentity> DEFAULT_IDENTITY_PROVIDER = noAuthIdentityProvider(); private static final HttpSigner<AnonymousIdentity> DEFAULT_SIGNER = noAuthSigner(); private static final AnonymousIdentity ANONYMOUS_IDENTITY = anonymousIdentity(); /** * Returns an instance of the {@link NoAuthAuthScheme}. */ public static NoAuthAuthScheme create() { return DEFAULT; } @Override public String schemeId() { return SCHEME_ID; } @Override public IdentityProvider<AnonymousIdentity> identityProvider(IdentityProviders providers) { return DEFAULT_IDENTITY_PROVIDER; } @Override public HttpSigner<AnonymousIdentity> signer() { return DEFAULT_SIGNER; } private static IdentityProvider<AnonymousIdentity> noAuthIdentityProvider() { return new IdentityProvider<AnonymousIdentity>() { @Override public Class identityType() { return AnonymousIdentity.class; } @Override public CompletableFuture<AnonymousIdentity> resolveIdentity(ResolveIdentityRequest request) { return CompletableFuture.completedFuture(ANONYMOUS_IDENTITY); } }; } private static HttpSigner<AnonymousIdentity> noAuthSigner() { return new HttpSigner<AnonymousIdentity>() { @Override public SignedRequest sign(SignRequest<? extends AnonymousIdentity> request) { return SignedRequest.builder() .request(request.request()) .payload(request.payload().orElse(null)) .build(); } @Override public CompletableFuture<AsyncSignedRequest> signAsync(AsyncSignRequest<? extends AnonymousIdentity> request) { return CompletableFuture.completedFuture( AsyncSignedRequest.builder() .request(request.request()) .payload(request.payload().orElse(null)) .build() ); } }; } private static AnonymousIdentity anonymousIdentity() { return new AnonymousIdentity() { }; } }
1,859
0
Create_ds/aws-sdk-java-v2/core/http-auth/src/main/java/software/amazon/awssdk/http/auth/internal
Create_ds/aws-sdk-java-v2/core/http-auth/src/main/java/software/amazon/awssdk/http/auth/internal/scheme/DefaultBearerAuthScheme.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.http.auth.internal.scheme; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.auth.scheme.BearerAuthScheme; import software.amazon.awssdk.http.auth.signer.BearerHttpSigner; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.identity.spi.IdentityProviders; import software.amazon.awssdk.identity.spi.TokenIdentity; /** * A default implementation of {@link BearerAuthScheme}. */ @SdkInternalApi public final class DefaultBearerAuthScheme implements BearerAuthScheme { private static final DefaultBearerAuthScheme DEFAULT = new DefaultBearerAuthScheme(); private static final BearerHttpSigner DEFAULT_SIGNER = BearerHttpSigner.create(); /** * Returns an instance of the {@link DefaultBearerAuthScheme}. */ public static DefaultBearerAuthScheme create() { return DEFAULT; } @Override public String schemeId() { return SCHEME_ID; } @Override public IdentityProvider<TokenIdentity> identityProvider(IdentityProviders providers) { return providers.identityProvider(TokenIdentity.class); } @Override public BearerHttpSigner signer() { return DEFAULT_SIGNER; } }
1,860
0
Create_ds/aws-sdk-java-v2/core/http-auth/src/main/java/software/amazon/awssdk/http/auth/internal
Create_ds/aws-sdk-java-v2/core/http-auth/src/main/java/software/amazon/awssdk/http/auth/internal/signer/DefaultBearerHttpSigner.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.http.auth.internal.signer; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.auth.signer.BearerHttpSigner; import software.amazon.awssdk.http.auth.spi.signer.AsyncSignRequest; import software.amazon.awssdk.http.auth.spi.signer.AsyncSignedRequest; import software.amazon.awssdk.http.auth.spi.signer.BaseSignRequest; import software.amazon.awssdk.http.auth.spi.signer.SignRequest; import software.amazon.awssdk.http.auth.spi.signer.SignedRequest; import software.amazon.awssdk.identity.spi.TokenIdentity; /** * A default implementation of {@link BearerHttpSigner}. */ @SdkInternalApi public final class DefaultBearerHttpSigner implements BearerHttpSigner { @Override public SignedRequest sign(SignRequest<? extends TokenIdentity> request) { return SignedRequest.builder() .request(doSign(request)) .payload(request.payload().orElse(null)) .build(); } @Override public CompletableFuture<AsyncSignedRequest> signAsync(AsyncSignRequest<? extends TokenIdentity> request) { return CompletableFuture.completedFuture( AsyncSignedRequest.builder() .request(doSign(request)) .payload(request.payload().orElse(null)) .build() ); } /** * Using {@link BaseSignRequest}, sign the request with a {@link BaseSignRequest} and re-build it. */ private SdkHttpRequest doSign(BaseSignRequest<?, ? extends TokenIdentity> request) { return request.request().toBuilder() .putHeader( "Authorization", buildAuthorizationHeader(request.identity())) .build(); } /** * Use a {@link TokenIdentity} to build an authorization header. */ private String buildAuthorizationHeader(TokenIdentity tokenIdentity) { return "Bearer " + tokenIdentity.token(); } }
1,861
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/org/bitpedia
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/org/bitpedia/util/Base32.java
/* * Copyright (PD) 2006 The Bitzi Corporation * Please see the end of this file for full license text. */ package org.bitpedia.util; /** * Base32 - encodes and decodes RFC3548 Base32 * (see http://www.faqs.org/rfcs/rfc3548.html ) * * @author Robert Kaye * @author Gordon Mohr */ public class Base32 { private static final String BASE_32_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; private static final int[] BASE_32_LOOKUP = { 0xFF, 0xFF, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, // '0', '1', '2', '3', '4', '5', '6', '7' 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // '8', '9', ':', ';', '<', '=', '>', '?' 0xFF, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, // '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G' 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, // 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O' 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, // 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W' 0x17, 0x18, 0x19, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 'X', 'Y', 'Z', '[', '\', ']', '^', '_' 0xFF, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, // '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g' 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, // 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o' 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, // 'p', 'q', 'r', 's', 't', 'u', 'v', 'w' 0x17, 0x18, 0x19, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF // 'x', 'y', 'z', '{', '|', '}', '~', 'DEL' }; /** * Encodes byte array to Base32 String. * * @param bytes Bytes to encode. * @return Encoded byte array <code>bytes</code> as a String. * */ public static String encode(final byte[] bytes) { int i = 0; int index = 0; int digit = 0; int currByte; int nextByte; StringBuilder base32 = new StringBuilder((bytes.length + 7) * 8 / 5); while (i < bytes.length) { currByte = (bytes[i] >= 0) ? bytes[i] : (bytes[i] + 256); // unsign /* Is the current digit going to span a byte boundary? */ if (index > 3) { if ((i + 1) < bytes.length) { nextByte = (bytes[i + 1] >= 0) ? bytes[i + 1] : (bytes[i + 1] + 256); } else { nextByte = 0; } digit = currByte & (0xFF >> index); index = (index + 5) % 8; digit <<= index; digit |= nextByte >> (8 - index); i++; } else { digit = (currByte >> (8 - (index + 5))) & 0x1F; index = (index + 5) % 8; if (index == 0) { i++; } } base32.append(BASE_32_CHARS.charAt(digit)); } return base32.toString(); } /** * Decodes the given Base32 String to a raw byte array. * * @return Decoded <code>base32</code> String as a raw byte array. */ public static byte[] decode(final String base32) { int i; int index; int lookup; int offset; int digit; byte[] bytes = new byte[base32.length() * 5 / 8]; for (i = 0, index = 0, offset = 0; i < base32.length(); i++) { lookup = base32.charAt(i) - '0'; /* Skip chars outside the lookup table. */ if (lookup < 0 || lookup >= BASE_32_LOOKUP.length) { continue; } digit = BASE_32_LOOKUP[lookup]; /* If this digit is not in the table, ignore it. */ if (digit == 0xFF) { continue; } if (index <= 3) { index = (index + 5) % 8; if (index == 0) { bytes[offset] |= digit; offset++; if (offset >= bytes.length) { break; } } else { bytes[offset] |= digit << (8 - index); } } else { index = (index + 5) % 8; bytes[offset] |= (digit >>> index); offset++; if (offset >= bytes.length) { break; } bytes[offset] |= digit << (8 - index); } } return bytes; } /** For testing, take a command-line argument in Base32, decode, print in hex, * encode, print * */ public static void main(String[] args) { if (args.length == 0) { System.out.println("Supply a Base32-encoded argument."); return; } System.out.println(" Original: " + args[0]); byte[] decoded = Base32.decode(args[0]); System.out.print(" Hex: "); for (final byte aDecoded : decoded) { int b = aDecoded; if (b < 0) { b += 256; } System.out.print((Integer.toHexString(b + 256)).substring(1)); } System.out.println(); System.out.println("Reencoded: " + Base32.encode(decoded)); } } /* (PD) 2003 The Bitzi Corporation * * 1. Authorship. This work and others bearing the above * label were created by, or on behalf of, the Bitzi * Corporation. Often other public domain material by * other authors is also incorporated; this should be * clear from notations in the source code. * * 2. Release. The Bitzi Corporation places these works * into the public domain, disclaiming all rights granted * us by copyright law. * * You are completely free to copy, use, redistribute * and modify this work, though you should be aware of * points (3) and (4), below. * * 3. Trademark Advisory. The Bitzi Corporation reserves * all rights with regard to any of its trademarks which * may appear herein, such as "Bitzi" or "Bitcollider". * Please take care that your uses of this work do not * infringe on our trademarks or imply our endorsement. * For example, you should change labels and identifier * strings in your derivative works where appropriate. * * 4. Disclaimer. THIS SOFTWARE IS PROVIDED BY THE AUTHOR * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Please see http://bitzi.com/publicdomain or write * info@bitzi.com for more info. */
1,862
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/utils/SdkSubscriberTest.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 utils; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import org.reactivestreams.Subscriber; import software.amazon.awssdk.core.pagination.async.AsyncPageFetcher; import software.amazon.awssdk.core.pagination.async.PaginatedItemsPublisher; import software.amazon.awssdk.utils.async.LimitingSubscriber; import software.amazon.awssdk.utils.internal.async.EmptySubscription; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.Function; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; @RunWith(MockitoJUnitRunner.class) public class SdkSubscriberTest { public static final Function<Integer, Iterator<Integer>> SAMPLE_ITERATOR = response -> Arrays.asList(1, 2, 3, 4, 5, 6).listIterator(); public static final Function<Integer, Iterator<Integer>> EMPTY_ITERATOR = response -> new ArrayList<Integer>().listIterator(); @Mock AsyncPageFetcher asyncPageFetcher; PaginatedItemsPublisher<Integer, Integer> itemsPublisher; @Mock Subscriber<Integer> mockSubscriber; @Before public void setUp() { doReturn(CompletableFuture.completedFuture(1)) .when(asyncPageFetcher).nextPage(null); doReturn(false) .when(asyncPageFetcher).hasNextPage(any()); } @Test public void limitingSubscriber_with_different_limits() throws InterruptedException, ExecutionException, TimeoutException { itemsPublisher = PaginatedItemsPublisher.builder().nextPageFetcher(asyncPageFetcher) .iteratorFunction(SAMPLE_ITERATOR).isLastPage(false).build(); final List<Integer> belowLimit = new ArrayList<>(); itemsPublisher.limit(3).subscribe(e -> belowLimit.add(e)).get(5, TimeUnit.SECONDS); assertThat(belowLimit).isEqualTo(Arrays.asList(1, 2, 3)); final List<Integer> beyondLimit = new ArrayList<>(); itemsPublisher.limit(33).subscribe(e -> beyondLimit.add(e)).get(5, TimeUnit.SECONDS); assertThat(beyondLimit).isEqualTo(Arrays.asList(1, 2, 3, 4, 5, 6)); final List<Integer> zeroLimit = new ArrayList<>(); itemsPublisher.limit(0).subscribe(e -> zeroLimit.add(e)).get(5, TimeUnit.SECONDS); assertThat(zeroLimit).isEqualTo(Arrays.asList()); } @Test public void filteringSubscriber_with_different_filters() throws InterruptedException, ExecutionException, TimeoutException { itemsPublisher = PaginatedItemsPublisher.builder().nextPageFetcher(asyncPageFetcher) .iteratorFunction(SAMPLE_ITERATOR).isLastPage(false).build(); final List<Integer> filteredSomeList = new ArrayList<>(); itemsPublisher.filter(i -> i % 2 == 0).subscribe(e -> filteredSomeList.add(e)).get(5, TimeUnit.SECONDS); assertThat(filteredSomeList).isEqualTo(Arrays.asList(2, 4, 6)); final List<Integer> filteredAllList = new ArrayList<>(); itemsPublisher.filter(i -> i % 10 == 0).subscribe(e -> filteredAllList.add(e)).get(5, TimeUnit.SECONDS); assertThat(filteredAllList).isEqualTo(Arrays.asList()); final List<Integer> filteredNone = new ArrayList<>(); itemsPublisher.filter(i -> i % 1 == 0).subscribe(e -> filteredNone.add(e)).get(5, TimeUnit.SECONDS); assertThat(filteredNone).isEqualTo(Arrays.asList(1, 2, 3, 4, 5, 6)); } @Test public void limit_and_filter_subscriber_chained_with_different_conditions() throws InterruptedException, ExecutionException, TimeoutException { itemsPublisher = PaginatedItemsPublisher.builder().nextPageFetcher(asyncPageFetcher) .iteratorFunction(SAMPLE_ITERATOR).isLastPage(false).build(); final List<Integer> belowLimitWithFiltering = new ArrayList<>(); itemsPublisher.limit(4).filter(i -> i % 2 == 0).subscribe(e -> belowLimitWithFiltering.add(e)).get(5, TimeUnit.SECONDS); assertThat(belowLimitWithFiltering).isEqualTo(Arrays.asList(2, 4)); final List<Integer> beyondLimitWithAllFiltering = new ArrayList<>(); itemsPublisher.limit(33).filter(i -> i % 10 == 0).subscribe(e -> beyondLimitWithAllFiltering.add(e)).get(5, TimeUnit.SECONDS); assertThat(beyondLimitWithAllFiltering).isEqualTo(Arrays.asList()); final List<Integer> zeroLimitAndNoFilter = new ArrayList<>(); itemsPublisher.limit(0).filter(i -> i % 1 == 0).subscribe(e -> zeroLimitAndNoFilter.add(e)).get(5, TimeUnit.SECONDS); assertThat(zeroLimitAndNoFilter).isEqualTo(Arrays.asList()); final List<Integer> filteringbelowLimitWith = new ArrayList<>(); itemsPublisher.filter(i -> i % 2 == 0).limit(2).subscribe(e -> filteringbelowLimitWith.add(e)).get(5, TimeUnit.SECONDS); assertThat(filteringbelowLimitWith).isEqualTo(Arrays.asList(2, 4)); final List<Integer> filteringAndOutsideLimit = new ArrayList<>(); itemsPublisher.filter(i -> i % 10 == 0).limit(33).subscribe(e -> filteringAndOutsideLimit.add(e)).get(5, TimeUnit.SECONDS); assertThat(filteringAndOutsideLimit).isEqualTo(Arrays.asList()); } @Test public void limit__subscriber_with_empty_input_and_zero_limit() throws InterruptedException, ExecutionException, TimeoutException { itemsPublisher = PaginatedItemsPublisher.builder().nextPageFetcher(asyncPageFetcher) .iteratorFunction(EMPTY_ITERATOR).isLastPage(false).build(); final List<Integer> zeroLimit = new ArrayList<>(); itemsPublisher.limit(0).subscribe(e -> zeroLimit.add(e)).get(5, TimeUnit.SECONDS); assertThat(zeroLimit).isEqualTo(Arrays.asList()); final List<Integer> nonZeroLimit = new ArrayList<>(); itemsPublisher.limit(10).subscribe(e -> nonZeroLimit.add(e)).get(5, TimeUnit.SECONDS); assertThat(zeroLimit).isEqualTo(Arrays.asList()); } @Test public void limiting_subscriber_with_multiple_thread_publishers() throws InterruptedException { final int limitFactor = 5; LimitingSubscriber<Integer> limitingSubscriber = new LimitingSubscriber<>(mockSubscriber, limitFactor); limitingSubscriber.onSubscribe(new EmptySubscription(mockSubscriber)); final ExecutorService executorService = Executors.newFixedThreadPool(10); for (int i = 0; i < 10; i++) { final Integer integer = Integer.valueOf(i); executorService.submit(() -> limitingSubscriber.onNext(new Integer(integer))); } executorService.awaitTermination(300, TimeUnit.MILLISECONDS); Mockito.verify(mockSubscriber, times(limitFactor)).onNext(anyInt()); Mockito.verify(mockSubscriber).onComplete(); Mockito.verify(mockSubscriber).onSubscribe(any()); Mockito.verify(mockSubscriber, never()).onError(any()); } }
1,863
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/utils/FakeSdkPublisher.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 utils; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.core.async.SdkPublisher; public class FakeSdkPublisher<T> implements SdkPublisher<T> { private Subscriber<? super T> delegateSubscriber; @Override public void subscribe(Subscriber<? super T> subscriber) { this.delegateSubscriber = subscriber; this.delegateSubscriber.onSubscribe(new FakeSubscription()); } public void publish(T str) { this.delegateSubscriber.onNext(str); } public void complete() { this.delegateSubscriber.onComplete(); } public void doThrow(Throwable t) { this.delegateSubscriber.onError(t); } private static final class FakeSubscription implements Subscription { @Override public void request(long n) { } @Override public void cancel() { } } }
1,864
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/utils/EmptySubscriptionTest.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 utils; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.reactivestreams.Subscriber; import software.amazon.awssdk.utils.internal.async.EmptySubscription; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @RunWith(MockitoJUnitRunner.class) public class EmptySubscriptionTest { @Mock private Subscriber<String> mockSubscriber; @Test public void emptySubscription_with_invalid_request() { EmptySubscription emptySubscription = new EmptySubscription(mockSubscriber); assertThatIllegalArgumentException().isThrownBy(() -> emptySubscription.request(-1)); } @Test public void emptySubscription_with_normal_execution() { EmptySubscription emptySubscription = new EmptySubscription(mockSubscriber); emptySubscription.request(1); verify(mockSubscriber).onComplete(); } @Test public void emptySubscription_when_terminated_externally() { EmptySubscription emptySubscription = new EmptySubscription(mockSubscriber); emptySubscription.cancel(); emptySubscription.request(1); verify(mockSubscriber, never()).onComplete(); } }
1,865
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/utils/FakePublisher.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 utils; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; public class FakePublisher<T> implements Publisher<T> { private Subscriber<? super T> delegateSubscriber; @Override public void subscribe(Subscriber<? super T> subscriber) { this.delegateSubscriber = subscriber; this.delegateSubscriber.onSubscribe(new FakeSubscription()); } public void publish(T str) { this.delegateSubscriber.onNext(str); } public void complete() { this.delegateSubscriber.onComplete(); } public void doThrow(Throwable t) { this.delegateSubscriber.onError(t); } private static final class FakeSubscription implements Subscription { @Override public void request(long n) { } @Override public void cancel() { } } }
1,866
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/utils/ValidSdkObjects.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 utils; import java.net.URI; import java.util.List; import java.util.Optional; import software.amazon.awssdk.core.RequestOverrideConfiguration; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.http.SdkHttpMethod; /** * A collection of objects (or object builder) pre-populated with all required fields. This allows tests to focus on what data * they care about, not necessarily what data is required. */ public final class ValidSdkObjects { private ValidSdkObjects() {} public static SdkRequest sdkRequest() { return new SdkRequest() { @Override public Optional<? extends RequestOverrideConfiguration> overrideConfiguration() { return Optional.empty(); } @Override public Builder toBuilder() { return null; } @Override public List<SdkField<?>> sdkFields() { return null; } }; } public static SdkHttpFullRequest.Builder sdkHttpFullRequest() { return sdkHttpFullRequest(80); } public static SdkHttpFullRequest.Builder sdkHttpFullRequest(int port) { return SdkHttpFullRequest.builder() .uri(URI.create("http://localhost")) .port(port) .putHeader("Host", "localhost") .method(SdkHttpMethod.GET); } public static SdkHttpFullResponse.Builder sdkHttpFullResponse() { return SdkHttpFullResponse.builder() .statusCode(200); } }
1,867
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/utils/HttpTestUtils.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 utils; import java.net.URI; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Executors; import java.util.stream.Collectors; import software.amazon.awssdk.core.client.config.SdkAdvancedAsyncClientOption; import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.core.internal.http.AmazonAsyncHttpClient; import software.amazon.awssdk.core.internal.http.AmazonSyncHttpClient; import software.amazon.awssdk.core.internal.http.loader.DefaultSdkAsyncHttpClientBuilder; import software.amazon.awssdk.core.internal.http.loader.DefaultSdkHttpClientBuilder; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.core.signer.NoOpSigner; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.SdkHttpConfigurationOption; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.utils.AttributeMap; public class HttpTestUtils { public static SdkHttpClient testSdkHttpClient() { return new DefaultSdkHttpClientBuilder().buildWithDefaults( AttributeMap.empty().merge(SdkHttpConfigurationOption.GLOBAL_HTTP_DEFAULTS)); } public static SdkAsyncHttpClient testSdkAsyncHttpClient() { return new DefaultSdkAsyncHttpClientBuilder().buildWithDefaults( AttributeMap.empty().merge(SdkHttpConfigurationOption.GLOBAL_HTTP_DEFAULTS)); } public static AmazonSyncHttpClient testAmazonHttpClient() { return testClientBuilder().httpClient(testSdkHttpClient()).build(); } public static AmazonAsyncHttpClient testAsyncHttpClient() { return new TestAsyncClientBuilder().asyncHttpClient(testSdkAsyncHttpClient()).build(); } public static TestClientBuilder testClientBuilder() { return new TestClientBuilder(); } public static TestAsyncClientBuilder testAsyncClientBuilder() { return new TestAsyncClientBuilder(); } public static SdkClientConfiguration testClientConfiguration() { return SdkClientConfiguration.builder() .option(SdkClientOption.EXECUTION_INTERCEPTORS, new ArrayList<>()) .option(SdkClientOption.ENDPOINT, URI.create("http://localhost:8080")) .option(SdkClientOption.RETRY_POLICY, RetryPolicy.defaultRetryPolicy()) .option(SdkClientOption.ADDITIONAL_HTTP_HEADERS, new HashMap<>()) .option(SdkClientOption.CRC32_FROM_COMPRESSED_DATA_ENABLED, false) .option(SdkAdvancedClientOption.SIGNER, new NoOpSigner()) .option(SdkAdvancedClientOption.USER_AGENT_PREFIX, "") .option(SdkAdvancedClientOption.USER_AGENT_SUFFIX, "") .option(SdkClientOption.SCHEDULED_EXECUTOR_SERVICE, Executors.newScheduledThreadPool(1)) .option(SdkAdvancedAsyncClientOption.FUTURE_COMPLETION_EXECUTOR, Runnable::run) .build(); } public static class TestClientBuilder { private RetryPolicy retryPolicy; private SdkHttpClient httpClient; private Map<String, String> additionalHeaders = new HashMap<>(); private Duration apiCallTimeout; private Duration apiCallAttemptTimeout; public TestClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } public TestClientBuilder httpClient(SdkHttpClient sdkHttpClient) { this.httpClient = sdkHttpClient; return this; } public TestClientBuilder additionalHeader(String key, String value) { this.additionalHeaders.put(key, value); return this; } public TestClientBuilder apiCallTimeout(Duration duration) { this.apiCallTimeout = duration; return this; } public TestClientBuilder apiCallAttemptTimeout(Duration timeout) { this.apiCallAttemptTimeout = timeout; return this; } public AmazonSyncHttpClient build() { SdkHttpClient sdkHttpClient = this.httpClient != null ? this.httpClient : testSdkHttpClient(); return new AmazonSyncHttpClient(testClientConfiguration().toBuilder() .option(SdkClientOption.SYNC_HTTP_CLIENT, sdkHttpClient) .applyMutation(this::configureRetryPolicy) .applyMutation(this::configureAdditionalHeaders) .option(SdkClientOption.API_CALL_TIMEOUT, apiCallTimeout) .option(SdkClientOption.API_CALL_ATTEMPT_TIMEOUT, apiCallAttemptTimeout) .build()); } private void configureAdditionalHeaders(SdkClientConfiguration.Builder builder) { Map<String, List<String>> headers = this.additionalHeaders.entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> Arrays.asList(e.getValue()))); builder.option(SdkClientOption.ADDITIONAL_HTTP_HEADERS, headers); } private void configureRetryPolicy(SdkClientConfiguration.Builder builder) { if (retryPolicy != null) { builder.option(SdkClientOption.RETRY_POLICY, retryPolicy); } } } public static class TestAsyncClientBuilder { private RetryPolicy retryPolicy; private SdkAsyncHttpClient asyncHttpClient; private Duration apiCallTimeout; private Duration apiCallAttemptTimeout; private Map<String, String> additionalHeaders = new HashMap<>(); public TestAsyncClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } public TestAsyncClientBuilder asyncHttpClient(SdkAsyncHttpClient asyncHttpClient) { this.asyncHttpClient = asyncHttpClient; return this; } public TestAsyncClientBuilder additionalHeader(String key, String value) { this.additionalHeaders.put(key, value); return this; } public TestAsyncClientBuilder apiCallTimeout(Duration duration) { this.apiCallTimeout = duration; return this; } public TestAsyncClientBuilder apiCallAttemptTimeout(Duration timeout) { this.apiCallAttemptTimeout = timeout; return this; } public AmazonAsyncHttpClient build() { SdkAsyncHttpClient asyncHttpClient = this.asyncHttpClient != null ? this.asyncHttpClient : testSdkAsyncHttpClient(); return new AmazonAsyncHttpClient(testClientConfiguration().toBuilder() .option(SdkClientOption.ASYNC_HTTP_CLIENT, asyncHttpClient) .option(SdkClientOption.API_CALL_TIMEOUT, apiCallTimeout) .option(SdkClientOption.API_CALL_ATTEMPT_TIMEOUT, apiCallAttemptTimeout) .applyMutation(this::configureRetryPolicy) .applyMutation(this::configureAdditionalHeaders) .build()); } private void configureAdditionalHeaders(SdkClientConfiguration.Builder builder) { Map<String, List<String>> headers = this.additionalHeaders.entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> Arrays.asList(e.getValue()))); builder.option(SdkClientOption.ADDITIONAL_HTTP_HEADERS, headers); } private void configureRetryPolicy(SdkClientConfiguration.Builder builder) { if (retryPolicy != null) { builder.option(SdkClientOption.RETRY_POLICY, retryPolicy); } } } }
1,868
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/utils
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/utils/retry/SimpleArrayBackoffStrategy.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 utils.retry; import java.time.Duration; import software.amazon.awssdk.core.retry.RetryPolicyContext; import software.amazon.awssdk.core.retry.backoff.BackoffStrategy; /** * Backoff strategy used in tests to pull backoff value from a backing array. Number of retries is * limited to size of array. */ public final class SimpleArrayBackoffStrategy implements BackoffStrategy { private final int[] backoffValues; public SimpleArrayBackoffStrategy(int[] backoffValues) { this.backoffValues = backoffValues; } @Override public Duration computeDelayBeforeNextRetry(RetryPolicyContext context) { return Duration.ofMillis(backoffValues[context.retriesAttempted()]); } }
1,869
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/utils
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/utils/http/WireMockTestBase.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 utils.http; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.net.URI; import org.junit.Rule; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.http.SdkHttpMethod; /** * Base class for tests that use a WireMock server */ public abstract class WireMockTestBase { @Rule public WireMockRule mockServer = new WireMockRule(0); protected SdkHttpFullRequest.Builder newGetRequest(String resourcePath) { return newRequest(resourcePath) .method(SdkHttpMethod.GET); } protected SdkHttpFullRequest.Builder newRequest(String resourcePath) { return SdkHttpFullRequest.builder() .uri(URI.create("http://localhost")) .port(mockServer.port()) .encodedPath(resourcePath); } protected HttpResponseHandler<SdkServiceException> stubErrorHandler() throws Exception { HttpResponseHandler<SdkServiceException> errorHandler = mock(HttpResponseHandler.class); when(errorHandler.handle(any(SdkHttpFullResponse.class), any(ExecutionAttributes.class))).thenReturn(mockException()); return errorHandler; } private SdkServiceException mockException() { SdkServiceException exception = SdkServiceException.builder().message("Dummy error response").statusCode(500).build(); return exception; } }
1,870
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/SdkBytesTest.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.core; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; public class SdkBytesTest { @Test public void fromByteArrayCreatesCopy() { byte[] input = new byte[] { 'a' }; byte[] output = SdkBytes.fromByteArray(input).asByteArrayUnsafe(); input[0] = 'b'; assertThat(output).isNotEqualTo(input); } @Test public void asByteArrayCreatesCopy() { byte[] input = new byte[] { 'a' }; byte[] output = SdkBytes.fromByteArrayUnsafe(input).asByteArray(); input[0] = 'b'; assertThat(output).isNotEqualTo(input); } @Test public void fromByteArrayUnsafeAndAsByteArrayUnsafeDoNotCopy() { byte[] input = new byte[] { 'a' }; byte[] output = SdkBytes.fromByteArrayUnsafe(input).asByteArrayUnsafe(); assertThat(output).isSameAs(input); } }
1,871
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/ResponseBytesTest.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.core; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; public class ResponseBytesTest { private static final Object OBJECT = new Object(); @Test public void fromByteArrayCreatesCopy() { byte[] input = new byte[] { 'a' }; byte[] output = ResponseBytes.fromByteArray(OBJECT, input).asByteArrayUnsafe(); input[0] = 'b'; assertThat(output).isNotEqualTo(input); } @Test public void asByteArrayCreatesCopy() { byte[] input = new byte[] { 'a' }; byte[] output = ResponseBytes.fromByteArrayUnsafe(OBJECT, input).asByteArray(); input[0] = 'b'; assertThat(output).isNotEqualTo(input); } @Test public void fromByteArrayUnsafeAndAsByteArrayUnsafeDoNotCopy() { byte[] input = new byte[] { 'a' }; byte[] output = ResponseBytes.fromByteArrayUnsafe(OBJECT, input).asByteArrayUnsafe(); assertThat(output).isSameAs(input); } }
1,872
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/FileTransformerConfigurationTest.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.core; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static software.amazon.awssdk.core.FileTransformerConfiguration.FailureBehavior.DELETE; import static software.amazon.awssdk.core.FileTransformerConfiguration.FileWriteOption.CREATE_NEW; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; class FileTransformerConfigurationTest { @Test void equalsHashcode() { EqualsVerifier.forClass(FileTransformerConfiguration.class) .withNonnullFields("fileWriteOption", "failureBehavior") .verify(); } @Test void toBuilder() { FileTransformerConfiguration configuration = FileTransformerConfiguration.builder() .failureBehavior(DELETE) .fileWriteOption(CREATE_NEW) .build(); FileTransformerConfiguration another = configuration.toBuilder().build(); assertThat(configuration).isEqualTo(another); } }
1,873
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/SdkNumberTest.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.core; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Objects; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledForJreRange; import org.junit.jupiter.api.condition.EnabledOnJre; import org.junit.jupiter.api.condition.JRE; public class SdkNumberTest { public static final String THIRTY_TWO_DIGITS = "100000000000000000000000000000000"; @Test public void integerSdkNumber() { final SdkNumber sdkNumber = SdkNumber.fromInteger(-100); assertThat(sdkNumber.bigDecimalValue()).isEqualTo(BigDecimal.valueOf(-100)); assertThat(sdkNumber.longValue()).isEqualTo(-100L); assertThat(sdkNumber.doubleValue()).isEqualTo(-100.0); assertThat(sdkNumber.floatValue()).isEqualTo(-100.0f); assertThat(sdkNumber.shortValue()).isEqualTo((short) -100); assertThat(sdkNumber.byteValue()).isEqualTo((byte) -100); assertThat(sdkNumber).hasToString("-100"); assertThat(SdkNumber.fromInteger(-100)).isEqualTo(sdkNumber); assertThat(Objects.hashCode(sdkNumber)).isEqualTo(Objects.hashCode(SdkNumber.fromInteger(-100))); } @Test public void longSdkNumber() { final SdkNumber sdkNumber = SdkNumber.fromLong(-123456789L); assertThat(sdkNumber.longValue()).isEqualTo(-123456789L); assertThat(sdkNumber.intValue()).isEqualTo(-123456789); assertThat(sdkNumber.bigDecimalValue()).isEqualTo(BigDecimal.valueOf(-123456789)); assertThat(sdkNumber.doubleValue()).isEqualTo(-123456789.0); assertThat(sdkNumber.floatValue()).isEqualTo(-123456789.0f); assertThat(sdkNumber.shortValue()).isEqualTo((short) -123456789); assertThat(sdkNumber.byteValue()).isEqualTo((byte) -123456789); assertThat(sdkNumber).hasToString("-123456789"); assertThat(SdkNumber.fromLong(-123456789L)).isEqualTo(sdkNumber); assertThat(Objects.hashCode(sdkNumber)).isEqualTo(Objects.hashCode(SdkNumber.fromLong(-123456789L))); } @Test public void doubleSdkNumber() { final SdkNumber sdkNumber = SdkNumber.fromDouble(-123456789.987654321); assertThat(sdkNumber.longValue()).isEqualTo(-123456789L); assertThat(sdkNumber.intValue()).isEqualTo(-123456789); assertThat(sdkNumber.bigDecimalValue()).isEqualTo(BigDecimal.valueOf(-123456789.987654321)); assertThat(sdkNumber.doubleValue()).isEqualTo(-123456789.987654321); assertThat(sdkNumber.floatValue()).isEqualTo(-123456789.987654321f); assertThat(sdkNumber.shortValue()).isEqualTo((short) -123456789); assertThat(sdkNumber.byteValue()).isEqualTo((byte) -123456789); assertThat(sdkNumber).hasToString("-1.2345678998765433E8"); assertThat(SdkNumber.fromDouble(-123456789.987654321)).isEqualTo(sdkNumber); assertThat(Objects.hashCode(sdkNumber)).isEqualTo(Objects.hashCode(SdkNumber.fromDouble(-123456789.987654321))); } @Test public void shortSdkNumber() { final SdkNumber sdkNumber = SdkNumber.fromShort((short) 2); assertThat(sdkNumber.longValue()).isEqualTo(2L); assertThat(sdkNumber.doubleValue()).isEqualTo(2); assertThat(sdkNumber.floatValue()).isEqualTo(2); assertThat(sdkNumber.shortValue()).isEqualTo((short) 2); assertThat(sdkNumber.byteValue()).isEqualTo((byte) 2); assertThat(sdkNumber).hasToString("2"); } @Test public void floatSdkNumber() { final SdkNumber sdkNumber = SdkNumber.fromFloat(-123456789.987654321f); assertThat(sdkNumber.longValue()).isEqualTo((long) -123456789.987654321f); assertThat(sdkNumber.intValue()).isEqualTo((int) -123456789.987654321f); assertThat(sdkNumber.bigDecimalValue()).isEqualTo(BigDecimal.valueOf(-123456789.987654321f)); assertThat(sdkNumber.doubleValue()).isEqualTo(-123456789.987654321f); assertThat(sdkNumber.floatValue()).isEqualTo(-123456789.987654321f); assertThat(sdkNumber.shortValue()).isEqualTo((short) -123456789.987654321f); assertThat(sdkNumber.byteValue()).isEqualTo((byte) -123456789.987654321f); } // JDK 19+ changes the float formatting: https://bugs.openjdk.org/browse/JDK-8300869 @Test @EnabledForJreRange(max = JRE.JAVA_18) public void floatSdkNumber_lt_jdk19() { SdkNumber sdkNumber = SdkNumber.fromFloat(-123456789.987654321f); assertThat(sdkNumber.toString()).isEqualTo("-1.23456792E8") .isEqualTo(Float.valueOf(-123456789.987654321f).toString()); } // JDK 19+ changes the float formatting: https://bugs.openjdk.org/browse/JDK-8300869 @Test @EnabledForJreRange(min = JRE.JAVA_19) public void floatSdkNumber_gt_jdk19() { SdkNumber sdkNumber = SdkNumber.fromFloat(-123456789.987654321f); assertThat(sdkNumber.toString()).isEqualTo("-1.2345679E8") .isEqualTo(Float.valueOf(-123456789.987654321f).toString()); } @Test public void bigDecimalSdkNumber() { final BigDecimal bigDecimalValue = new BigDecimal(-123456789.987654321); final SdkNumber sdkNumber = SdkNumber.fromBigDecimal(bigDecimalValue); assertThat(sdkNumber.longValue()).isEqualTo(bigDecimalValue.longValue()); assertThat(sdkNumber.intValue()).isEqualTo(bigDecimalValue.intValue()); assertThat(sdkNumber.bigDecimalValue()).isEqualTo(new BigDecimal(-123456789.987654321)); assertThat(sdkNumber.doubleValue()).isEqualByComparingTo(-123456789.987654321); assertThat(sdkNumber.floatValue()).isEqualTo(-123456789.987654321f); assertThat(sdkNumber.shortValue()).isEqualTo(bigDecimalValue.shortValue()); assertThat(sdkNumber.byteValue()).isEqualTo(bigDecimalValue.byteValue()); assertThat(sdkNumber).hasToString(bigDecimalValue.toString()); assertThat(SdkNumber.fromBigDecimal(new BigDecimal(-123456789.987654321))).isEqualTo(sdkNumber); assertThat(Objects.hashCode(sdkNumber)).isEqualTo(Objects.hashCode(SdkNumber.fromBigDecimal(new BigDecimal(-123456789.987654321)))); } @Test public void numberFromString() { final SdkNumber sdkSmallNumber = SdkNumber.fromString("1"); assertThat(sdkSmallNumber.longValue()).isEqualTo(1L); assertThat(sdkSmallNumber.stringValue()).isEqualTo("1"); assertThat(sdkSmallNumber.bigDecimalValue()).isEqualTo(new BigDecimal(1)); assertThat(sdkSmallNumber.shortValue()).isEqualTo((short) 1); assertThat(sdkSmallNumber.intValue()).isEqualTo(1); final SdkNumber sdkBigDecimalNumber = SdkNumber.fromString(THIRTY_TWO_DIGITS + ".123456789000000"); final BigDecimal bigDecimal = new BigDecimal(THIRTY_TWO_DIGITS + ".123456789000000"); assertThat(sdkBigDecimalNumber.bigDecimalValue()).isEqualTo(bigDecimal); assertThat(sdkBigDecimalNumber.longValue()).isEqualTo(bigDecimal.longValue()); assertThat(sdkBigDecimalNumber.bigDecimalValue()).isEqualTo(bigDecimal); assertThat(sdkBigDecimalNumber.intValue()).isEqualTo(bigDecimal.intValue()); assertThat(sdkBigDecimalNumber.shortValue()).isEqualTo(bigDecimal.shortValue()); assertThat(sdkBigDecimalNumber.intValue()).isEqualTo(bigDecimal.intValue()); assertThat(sdkBigDecimalNumber.doubleValue()).isEqualTo(bigDecimal.doubleValue()); assertThat(SdkNumber.fromString("1")).isEqualTo(sdkSmallNumber); assertThat(Objects.hashCode(sdkSmallNumber)).isEqualTo(Objects.hashCode(SdkNumber.fromString("1"))); assertThat(sdkBigDecimalNumber).isEqualTo(SdkNumber.fromBigDecimal(bigDecimal)); assertThat(Objects.hashCode(sdkBigDecimalNumber)).isEqualTo(Objects.hashCode(SdkNumber.fromBigDecimal(bigDecimal))); assertThat(sdkBigDecimalNumber.equals(sdkBigDecimalNumber)).isTrue(); } @Test public void numberFromNaNDouble() { final SdkNumber sdkNan = SdkNumber.fromDouble(Double.NaN); final Double nanDouble = Double.NaN; assertThat(nanDouble.isNaN()).isTrue(); assertThatThrownBy(() -> sdkNan.bigDecimalValue()).isInstanceOf(NumberFormatException.class); assertEqualitySDKNumberWithNumber(sdkNan, nanDouble); } @Test public void numberFromNaNFloat() { final SdkNumber sdkNan = SdkNumber.fromFloat(Float.NaN); final Float floatNan = Float.NaN; assertThat(floatNan.isNaN()).isTrue(); assertThatThrownBy(() -> sdkNan.bigDecimalValue()).isInstanceOf(NumberFormatException.class); assertEqualitySDKNumberWithNumber(sdkNan, floatNan); } @Test public void numberFromPositiveInfinityDouble() { final SdkNumber sdkNan = SdkNumber.fromDouble(Double.POSITIVE_INFINITY); final Double positiveInfinity = Double.POSITIVE_INFINITY; assertThat(positiveInfinity.isInfinite()).isTrue(); assertThatThrownBy(() -> sdkNan.bigDecimalValue()).isInstanceOf(NumberFormatException.class); assertEqualitySDKNumberWithNumber(sdkNan, positiveInfinity); } @Test public void numberFromNegativeInfinityDouble() { final SdkNumber sdkNan = SdkNumber.fromDouble(Double.NEGATIVE_INFINITY); final Double positiveInfinity = Double.NEGATIVE_INFINITY; assertThat(positiveInfinity.isInfinite()).isTrue(); assertThatThrownBy(() -> sdkNan.bigDecimalValue()).isInstanceOf(NumberFormatException.class); assertEqualitySDKNumberWithNumber(sdkNan, positiveInfinity); } public void numberFromPositiveInfinityFloat() { final SdkNumber sdkNan = SdkNumber.fromFloat(Float.POSITIVE_INFINITY); final Float positiveInfinity = Float.POSITIVE_INFINITY; assertThat(positiveInfinity.isNaN()).isTrue(); assertThatThrownBy(() -> sdkNan.bigDecimalValue()).isInstanceOf(NumberFormatException.class); assertEqualitySDKNumberWithNumber(sdkNan, positiveInfinity); } @Test public void numberFromNegativeInfinityFLoat() { final SdkNumber sdkNan = SdkNumber.fromFloat(Float.NEGATIVE_INFINITY); final Float positiveInfinity = Float.NEGATIVE_INFINITY; assertThat(positiveInfinity.isInfinite()).isTrue(); assertThatThrownBy(() -> sdkNan.bigDecimalValue()).isInstanceOf(NumberFormatException.class); assertEqualitySDKNumberWithNumber(sdkNan, positiveInfinity); } private void assertEqualitySDKNumberWithNumber(SdkNumber sdkNan, Number nanDouble) { assertThat(sdkNan.longValue()).isEqualTo(nanDouble.longValue()); assertThat(sdkNan.stringValue()).isEqualTo(nanDouble.toString()); assertThat(sdkNan.shortValue()).isEqualTo(nanDouble.shortValue()); assertThat(sdkNan.intValue()).isEqualTo(nanDouble.intValue()); assertThat(sdkNan).hasToString(nanDouble.toString()); assertThat(sdkNan.byteValue()).isEqualTo(nanDouble.byteValue()); // convert to nullable Double to prevent comparison of primitives because Double.NaN == Double.NaN is false assertThat(Double.valueOf(sdkNan.doubleValue())).isEqualTo(Double.valueOf(nanDouble.doubleValue())); assertThat(sdkNan.byteValue()).isEqualTo(nanDouble.byteValue()); } @Test public void bigIntegerNumber() { final SdkNumber sdkNumber = SdkNumber.fromBigInteger(new BigInteger(THIRTY_TWO_DIGITS)); BigInteger bigIntegerExpected = new BigInteger(THIRTY_TWO_DIGITS); assertEqualitySDKNumberWithNumber(sdkNumber, bigIntegerExpected); } @Test public void sdkNumberNotEqualToPrimitive(){ assertThat(SdkNumber.fromInteger(2)).isNotEqualTo(2); } }
1,874
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/RequestOverrideConfigurationTest.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.core; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.Mockito.mock; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.interceptor.ExecutionAttribute; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.metrics.MetricPublisher; import software.amazon.awssdk.utils.ImmutableMap; public class RequestOverrideConfigurationTest { private static final ConcurrentMap<String, ExecutionAttribute<Object>> ATTR_POOL = new ConcurrentHashMap<>(); private static ExecutionAttribute<Object> attr(String name) { name = RequestOverrideConfigurationTest.class.getName() + ":" + name; return ATTR_POOL.computeIfAbsent(name, ExecutionAttribute::new); } private static final String HEADER = "header"; private static final String QUERY_PARAM = "queryparam"; @Test public void equalsHashcode() { EqualsVerifier.forClass(RequestOverrideConfiguration.class) .usingGetClass() .verify(); } @Test public void toBuilder_minimal() { RequestOverrideConfiguration configuration = SdkRequestOverrideConfiguration.builder() .build(); assertThat(configuration.toBuilder().build()).usingRecursiveComparison().isEqualTo(configuration); } @Test public void toBuilder_maximal() { ExecutionAttribute testAttribute = attr("TestAttribute"); String expectedValue = "Value1"; RequestOverrideConfiguration configuration = SdkRequestOverrideConfiguration.builder() .putHeader(HEADER, "foo") .putRawQueryParameter(QUERY_PARAM, "foo") .addApiName(a -> a.name("test1").version("1")) .apiCallTimeout(Duration.ofSeconds(1)) .apiCallAttemptTimeout(Duration.ofSeconds(1)) .signer(new NoOpSigner()) .executionAttributes(ExecutionAttributes.builder().put(testAttribute, expectedValue).build()) .addMetricPublisher(mock(MetricPublisher.class)) .build(); assertThat(configuration.toBuilder().build()).usingRecursiveComparison().isEqualTo(configuration); } @Test public void addingSameItemTwice_shouldOverride() { RequestOverrideConfiguration configuration = SdkRequestOverrideConfiguration.builder() .putHeader(HEADER, "foo") .putHeader(HEADER, "bar") .putRawQueryParameter(QUERY_PARAM, "foo") .putRawQueryParameter(QUERY_PARAM, "bar") .addApiName(a -> a.name("test1").version("1")) .addApiName(a -> a.name("test2").version("2")) .build(); assertThat(configuration.headers().get(HEADER)).containsExactly("bar"); assertThat(configuration.rawQueryParameters().get(QUERY_PARAM)).containsExactly("bar"); assertThat(configuration.apiNames().size()).isEqualTo(2); } @Test public void settingCollection_shouldOverrideAddItem() { ImmutableMap<String, List<String>> map = ImmutableMap.of(HEADER, Arrays.asList("hello", "world")); ImmutableMap<String, List<String>> queryMap = ImmutableMap.of(QUERY_PARAM, Arrays.asList("hello", "world")); RequestOverrideConfiguration configuration = SdkRequestOverrideConfiguration.builder() .putHeader(HEADER, "blah") .headers(map) .putRawQueryParameter(QUERY_PARAM, "blah") .rawQueryParameters(queryMap) .build(); assertThat(configuration.headers().get(HEADER)).containsExactly("hello", "world"); assertThat(configuration.rawQueryParameters().get(QUERY_PARAM)).containsExactly("hello", "world"); } @Test public void addSameItemAfterSetCollection_shouldOverride() { ImmutableMap<String, List<String>> map = ImmutableMap.of(HEADER, Arrays.asList("hello", "world")); RequestOverrideConfiguration configuration = SdkRequestOverrideConfiguration.builder() .headers(map) .putHeader(HEADER, "blah") .build(); assertThat(configuration.headers().get(HEADER)).containsExactly("blah"); } @Test public void shouldGuaranteeImmutability() { List<String> headerValues = new ArrayList<>(); headerValues.add("bar"); Map<String, List<String>> headers = new HashMap<>(); headers.put("foo", headerValues); SdkRequestOverrideConfiguration.Builder configurationBuilder = SdkRequestOverrideConfiguration.builder().headers(headers); headerValues.add("test"); headers.put("new header", Collections.singletonList("new value")); assertThat(configurationBuilder.headers().size()).isEqualTo(1); assertThat(configurationBuilder.headers().get("foo")).containsExactly("bar"); } @Test public void metricPublishers_createsCopy() { List<MetricPublisher> publishers = new ArrayList<>(); publishers.add(mock(MetricPublisher.class)); List<MetricPublisher> toModify = new ArrayList<>(publishers); SdkRequestOverrideConfiguration overrideConfig = SdkRequestOverrideConfiguration.builder() .metricPublishers(toModify) .build(); toModify.clear(); assertThat(overrideConfig.metricPublishers()).isEqualTo(publishers); } @Test public void addMetricPublisher_maintainsAllAdded() { List<MetricPublisher> publishers = new ArrayList<>(); publishers.add(mock(MetricPublisher.class)); publishers.add(mock(MetricPublisher.class)); publishers.add(mock(MetricPublisher.class)); SdkRequestOverrideConfiguration.Builder builder = SdkRequestOverrideConfiguration.builder(); publishers.forEach(builder::addMetricPublisher); SdkRequestOverrideConfiguration overrideConfig = builder.build(); assertThat(overrideConfig.metricPublishers()).isEqualTo(publishers); } @Test public void metricPublishers_overwritesPreviouslyAdded() { MetricPublisher firstAdded = mock(MetricPublisher.class); List<MetricPublisher> publishers = new ArrayList<>(); publishers.add(mock(MetricPublisher.class)); publishers.add(mock(MetricPublisher.class)); SdkRequestOverrideConfiguration.Builder builder = SdkRequestOverrideConfiguration.builder(); builder.addMetricPublisher(firstAdded); builder.metricPublishers(publishers); SdkRequestOverrideConfiguration overrideConfig = builder.build(); assertThat(overrideConfig.metricPublishers()).isEqualTo(publishers); } @Test public void addMetricPublisher_listPreviouslyAdded_appendedToList() { List<MetricPublisher> publishers = new ArrayList<>(); publishers.add(mock(MetricPublisher.class)); publishers.add(mock(MetricPublisher.class)); MetricPublisher thirdAdded = mock(MetricPublisher.class); SdkRequestOverrideConfiguration.Builder builder = SdkRequestOverrideConfiguration.builder(); builder.metricPublishers(publishers); builder.addMetricPublisher(thirdAdded); SdkRequestOverrideConfiguration overrideConfig = builder.build(); assertThat(overrideConfig.metricPublishers()).containsExactly(publishers.get(0), publishers.get(1), thirdAdded); } @Test public void executionAttributes_createsCopy() { ExecutionAttributes executionAttributes = new ExecutionAttributes(); ExecutionAttribute testAttribute = attr("TestAttribute"); String expectedValue = "Value1"; executionAttributes.putAttribute(testAttribute, expectedValue); SdkRequestOverrideConfiguration overrideConfig = SdkRequestOverrideConfiguration.builder() .executionAttributes(executionAttributes) .build(); executionAttributes.putAttribute(testAttribute, "Value2"); assertThat(overrideConfig.executionAttributes().getAttribute(testAttribute)).isEqualTo(expectedValue); } @Test public void executionAttributes_isImmutable() { ExecutionAttributes executionAttributes = new ExecutionAttributes(); ExecutionAttribute testAttribute = attr("TestAttribute"); String expectedValue = "Value1"; executionAttributes.putAttribute(testAttribute, expectedValue); SdkRequestOverrideConfiguration overrideConfig = SdkRequestOverrideConfiguration.builder() .executionAttributes(executionAttributes) .build(); try { overrideConfig.executionAttributes().putAttribute(testAttribute, 2); fail("Expected unsupported operation exception"); } catch(Exception ex) { assertThat(ex instanceof UnsupportedOperationException).isTrue(); } try { overrideConfig.executionAttributes().putAttributeIfAbsent(testAttribute, 2); fail("Expected unsupported operation exception"); } catch(Exception ex) { assertThat(ex instanceof UnsupportedOperationException).isTrue(); } } @Test public void executionAttributes_maintainsAllAdded() { Map<ExecutionAttribute, Object> executionAttributeObjectMap = new HashMap<>(); for (int i = 0; i < 5; i++) { executionAttributeObjectMap.put(attr("Attribute" + i), mock(Object.class)); } SdkRequestOverrideConfiguration.Builder builder = SdkRequestOverrideConfiguration.builder(); for (Map.Entry<ExecutionAttribute, Object> attributeObjectEntry : executionAttributeObjectMap.entrySet()) { builder.putExecutionAttribute(attributeObjectEntry.getKey(), attributeObjectEntry.getValue()); } SdkRequestOverrideConfiguration overrideConfig = builder.build(); assertThat(overrideConfig.executionAttributes().getAttributes()).isEqualTo(executionAttributeObjectMap); } @Test public void executionAttributes_overwritesPreviouslyAdded() { ExecutionAttributes executionAttributes = new ExecutionAttributes(); for (int i = 0; i < 5; i++) { executionAttributes.putAttribute(attr("Attribute" + i), mock(Object.class)); } SdkRequestOverrideConfiguration.Builder builder = SdkRequestOverrideConfiguration.builder(); builder.putExecutionAttribute(attr("AddedAttribute"), mock(Object.class)); builder.executionAttributes(executionAttributes); SdkRequestOverrideConfiguration overrideConfig = builder.build(); assertThat(overrideConfig.executionAttributes().getAttributes()).isEqualTo(executionAttributes.getAttributes()); } @Test public void executionAttributes_listPreviouslyAdded_appendedToList() { ExecutionAttributes executionAttributes = new ExecutionAttributes(); for (int i = 0; i < 5; i++) { executionAttributes.putAttribute(attr("Attribute" + i), mock(Object.class)); } SdkRequestOverrideConfiguration.Builder builder = SdkRequestOverrideConfiguration.builder(); builder.executionAttributes(executionAttributes); ExecutionAttribute addedAttribute = attr("AddedAttribute"); Object addedValue = mock(Object.class); builder.putExecutionAttribute(addedAttribute, addedValue); SdkRequestOverrideConfiguration overrideConfig = builder.build(); assertThat(overrideConfig.executionAttributes().getAttribute(addedAttribute)).isEqualTo(addedValue); } @Test public void testConfigurationEquals() { ExecutionAttributes executionAttributes = new ExecutionAttributes(); for (int i = 0; i < 5; i++) { executionAttributes.putAttribute(attr("Attribute" + i), mock(Object.class)); } SdkRequestOverrideConfiguration request1Override = SdkRequestOverrideConfiguration.builder() .apiCallTimeout(Duration.ofMinutes(1)) .executionAttributes(executionAttributes) .build(); SdkRequestOverrideConfiguration request2Override = SdkRequestOverrideConfiguration.builder() .apiCallTimeout(Duration.ofMinutes(1)) .executionAttributes(executionAttributes) .build(); assertThat(request1Override).isEqualTo(request1Override); assertThat(request1Override).isEqualTo(request2Override); assertThat(request1Override).isNotEqualTo(null); } private static class NoOpSigner implements Signer { @Override public SdkHttpFullRequest sign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes) { return null; } } }
1,875
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/CredentialTypeTest.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.core; import static org.assertj.core.api.Assertions.as; import static org.assertj.core.api.Assertions.assertThat; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; public class CredentialTypeTest { @Test public void equalsHashcode() { EqualsVerifier.forClass(CredentialType.class) .withNonnullFields("value") .verify(); } @Test public void credentialType_bearerToken(){ CredentialType token = CredentialType.TOKEN; CredentialType tokenFromString = CredentialType.of("TOKEN"); assertThat(token).isSameAs(tokenFromString); assertThat(token).isEqualTo(tokenFromString); } @Test public void credentialType_usesSameInstance_when_sameCredentialTypeOfSameValue(){ CredentialType credentialTypeOne = CredentialType.of("Credential Type 1"); CredentialType credentialTypeOneDuplicate = CredentialType.of("Credential Type 1"); assertThat(credentialTypeOneDuplicate).isSameAs(credentialTypeOne); assertThat(credentialTypeOne).isEqualTo(credentialTypeOneDuplicate); } }
1,876
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/CompressionConfigurationTest.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.core; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; public class CompressionConfigurationTest { @Test public void equalsHashcode() { EqualsVerifier.forClass(CompressionConfiguration.class) .withNonnullFields("requestCompressionEnabled", "minimumCompressionThresholdInBytes") .verify(); } @Test public void toBuilder() { CompressionConfiguration configuration = CompressionConfiguration.builder() .requestCompressionEnabled(true) .minimumCompressionThresholdInBytes(99999) .build(); CompressionConfiguration another = configuration.toBuilder().build(); assertThat(configuration).isEqualTo(another); } }
1,877
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/FileRequestBodyConfigurationTest.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.core; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.nio.file.Paths; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; public class FileRequestBodyConfigurationTest { @Test void equalsHashCode() { EqualsVerifier.forClass(FileRequestBodyConfiguration.class) .verify(); } @Test void invalidRequest_shouldThrowException() { assertThatThrownBy(() -> FileRequestBodyConfiguration.builder() .path(Paths.get(".")) .position(-1L) .build()) .hasMessage("position must not be negative"); assertThatThrownBy(() -> FileRequestBodyConfiguration.builder() .path(Paths.get(".")) .numBytesToRead(-1L) .build()) .hasMessage("numBytesToRead must not be negative"); assertThatThrownBy(() -> FileRequestBodyConfiguration.builder() .path(Paths.get(".")) .chunkSizeInBytes(0) .build()) .hasMessage("chunkSizeInBytes must be positive"); assertThatThrownBy(() -> FileRequestBodyConfiguration.builder() .path(Paths.get(".")) .chunkSizeInBytes(-5) .build()) .hasMessage("chunkSizeInBytes must be positive"); assertThatThrownBy(() -> FileRequestBodyConfiguration.builder() .build()) .hasMessage("path"); } @Test void toBuilder_shouldCopyAllProperties() { FileRequestBodyConfiguration config = FileRequestBodyConfiguration.builder() .path(Paths.get(".")).numBytesToRead(100L) .position(1L) .chunkSizeInBytes(1024) .build(); assertThat(config.toBuilder().build()).isEqualTo(config); } }
1,878
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/pagination/PaginatedItemsIterableTest.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.core.pagination; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.Iterator; import java.util.function.Function; import org.junit.Before; 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.pagination.sync.PaginatedItemsIterable; import software.amazon.awssdk.core.pagination.sync.SdkIterable; @RunWith(MockitoJUnitRunner.class) public class PaginatedItemsIterableTest { @Mock private SdkIterable pagesIterable; @Mock private Iterator pagesIterator; @Mock private Function getItemIteratorFunction; @Mock private Iterator singlePageItemsIterator; private PaginatedItemsIterable itemsIterable; @Before public void setup() { when(pagesIterable.iterator()).thenReturn(pagesIterator); when(getItemIteratorFunction.apply(any())).thenReturn(singlePageItemsIterator); itemsIterable = PaginatedItemsIterable.builder() .pagesIterable(pagesIterable) .itemIteratorFunction(getItemIteratorFunction) .build(); } @Test public void hasNext_ReturnsFalse_WhenItemsAndPagesIteratorHasNoNextElement() { when(pagesIterator.hasNext()).thenReturn(false); assertFalse(itemsIterable.iterator().hasNext()); } @Test public void hasNext_ReturnsTrue_WhenItemsIteratorHasNextElement() { when(pagesIterator.hasNext()).thenReturn(true); when(getItemIteratorFunction.apply(any())).thenReturn(singlePageItemsIterator); when(singlePageItemsIterator.hasNext()).thenReturn(true); assertTrue(itemsIterable.iterator().hasNext()); } @Test public void hasNextMethodDoesNotRetrieveNextPage_WhenItemsIteratorHasAnElement() { when(pagesIterator.hasNext()).thenReturn(true); when(getItemIteratorFunction.apply(any())).thenReturn(singlePageItemsIterator); when(singlePageItemsIterator.hasNext()).thenReturn(true); Iterator itemsIterator = itemsIterable.iterator(); itemsIterator.hasNext(); itemsIterator.hasNext(); // pagesIterator.next() is called only once in ItemsIterator constructor // Not called again in ItemsIterator.hasNext() method verify(pagesIterator, times(1)).next(); } @Test public void hasNextMethodGetsNextPage_WhenCurrentItemsIteratorHasNoElements() { when(pagesIterator.hasNext()).thenReturn(true); when(singlePageItemsIterator.hasNext()).thenReturn(false) .thenReturn(true); itemsIterable.iterator().hasNext(); // pagesIterator.next() is called only once in ItemsIterator constructor // Called second time in hasNext() method verify(pagesIterator, times(2)).next(); } @Test public void hasNextMethodGetsNextPage_WhenCurrentItemsIteratorIsEmpty() { when(pagesIterator.hasNext()).thenReturn(true); when(getItemIteratorFunction.apply(any())).thenReturn(singlePageItemsIterator); when(singlePageItemsIterator.hasNext()).thenReturn(false, true); itemsIterable.iterator().hasNext(); // pagesIterator.next() is called only once in ItemsIterator constructor // Called second time in hasNext() method verify(pagesIterator, times(2)).next(); } @Test public void testNextMethod_WhenIntermediatePages_HasEmptyCollectionOfItems() { when(pagesIterator.hasNext()).thenReturn(true); // first page has empty items iterator Iterator itemsIterator1 = Mockito.mock(Iterator.class); when(itemsIterator1.hasNext()).thenReturn(false); // second page has empty items iterator Iterator itemsIterator2 = Mockito.mock(Iterator.class); when(itemsIterator2.hasNext()).thenReturn(false); // third page has empty items iterator Iterator itemsIterator3 = Mockito.mock(Iterator.class); when(itemsIterator3.hasNext()).thenReturn(false); // fourth page is non empty Iterator itemsIterator4 = Mockito.mock(Iterator.class); when(itemsIterator4.hasNext()).thenReturn(true); when(getItemIteratorFunction.apply(any())).thenReturn(itemsIterator1, itemsIterator2, itemsIterator3, itemsIterator4); itemsIterable.iterator().next(); verify(itemsIterator1, times(0)).next(); verify(itemsIterator2, times(0)).next(); verify(itemsIterator3, times(0)).next(); verify(itemsIterator4, times(1)).next(); verify(getItemIteratorFunction, times(4)).apply(any()); } }
1,879
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/pagination
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/pagination/async/PaginatedItemsPublisherTckTest.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.core.pagination.async; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.LongStream; import org.reactivestreams.Publisher; import org.reactivestreams.tck.PublisherVerification; import org.reactivestreams.tck.TestEnvironment; /** * TCK verification test for {@link PaginatedItemsPublisher}. */ public class PaginatedItemsPublisherTckTest extends PublisherVerification<Long> { public PaginatedItemsPublisherTckTest() { super(new TestEnvironment()); } @Override public Publisher<Long> createPublisher(long l) { Function<List<Long>, Iterator<Long>> getIterator = response -> response != null ? response.iterator() : Collections.emptyIterator(); return PaginatedItemsPublisher.builder() .nextPageFetcher(new PageFetcher(l, 5)) .iteratorFunction(getIterator) .isLastPage(false) .build(); } @Override public Publisher<Long> createFailedPublisher() { // It's not possible to initialize PaginatedItemsPublisher to a failed // state since we can only reach a failed state if we fail to fulfill a // request, e.g. because the service returned an error response. // return null to skip related tests return null; } /** * Simple {@link AsyncPageFetcher} that returns lists of longs as pages. */ private static class PageFetcher implements AsyncPageFetcher<List<Long>> { private final long maxVal; private final long step; private PageFetcher(long maxVal, long step) { this.maxVal = maxVal; this.step = step; } @Override public boolean hasNextPage(List<Long> oldPage) { return (lastElement(oldPage)) < maxVal - 1; } @Override public CompletableFuture<List<Long>> nextPage(List<Long> oldPage) { long i = lastElement(oldPage) + 1; long j = Math.min(i + step, maxVal); List<Long> stream = LongStream.range(i, j).boxed().collect(Collectors.toList()); return CompletableFuture.completedFuture(stream); } private long lastElement(List<Long> s) { // first page is always null if (s == null) return -1; return s.get(s.size() - 1); } } }
1,880
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/retry/AndRetryConditionTest.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.core.retry; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.when; import org.junit.Before; 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.retry.conditions.AndRetryCondition; import software.amazon.awssdk.core.retry.conditions.RetryCondition; @RunWith(MockitoJUnitRunner.class) public class AndRetryConditionTest { @Mock private RetryCondition conditionOne; @Mock private RetryCondition conditionTwo; private RetryCondition andCondition; @Before public void setup() { andCondition = AndRetryCondition.create(conditionOne, conditionTwo); } @Test public void allFalseConditions_ReturnsFalse() { assertFalse(andCondition.shouldRetry(RetryPolicyContexts.EMPTY)); } @Test public void onlyFirstConditionIsTrue_ReturnsFalse() { when(conditionOne.shouldRetry(any(RetryPolicyContext.class))) .thenReturn(true); assertFalse(andCondition.shouldRetry(RetryPolicyContexts.EMPTY)); } @Test public void onlySecondConditionIsTrue_ReturnsFalse() { assertFalse(andCondition.shouldRetry(RetryPolicyContexts.EMPTY)); } @Test public void bothConditionsAreTrue_ReturnsTrue() { when(conditionOne.shouldRetry(any(RetryPolicyContext.class))) .thenReturn(true); when(conditionTwo.shouldRetry(any(RetryPolicyContext.class))) .thenReturn(true); assertTrue(andCondition.shouldRetry(RetryPolicyContexts.EMPTY)); } /** * The expected result for an AND condition with no conditions is a little unclear so we disallow it until there is a use * case. */ @Test(expected = IllegalArgumentException.class) public void noConditions_ThrowsException() { AndRetryCondition.create().shouldRetry(RetryPolicyContexts.EMPTY); } @Test public void singleConditionThatReturnsTrue_ReturnsTrue() { when(conditionOne.shouldRetry(RetryPolicyContexts.EMPTY)) .thenReturn(true); assertTrue(AndRetryCondition.create(conditionOne).shouldRetry(RetryPolicyContexts.EMPTY)); } @Test public void singleConditionThatReturnsFalse_ReturnsFalse() { when(conditionOne.shouldRetry(RetryPolicyContexts.EMPTY)) .thenReturn(false); assertFalse(AndRetryCondition.create(conditionOne).shouldRetry(RetryPolicyContexts.EMPTY)); } @Test public void conditionsAreEvaluatedInOrder() { int numConditions = 1000; int firstFalseCondition = 500; RetryCondition[] conditions = new RetryCondition[numConditions]; for (int i = 0; i < numConditions; ++i) { RetryCondition mock = Mockito.mock(RetryCondition.class); when(mock.shouldRetry(RetryPolicyContexts.EMPTY)).thenReturn(i != firstFalseCondition); conditions[i] = mock; } assertFalse(AndRetryCondition.create(conditions).shouldRetry(RetryPolicyContexts.EMPTY)); for (int i = 0; i < numConditions; ++i) { int timesExpected = i <= firstFalseCondition ? 1 : 0; Mockito.verify(conditions[i], times(timesExpected)).shouldRetry(RetryPolicyContexts.EMPTY); } } }
1,881
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/retry/FixedTimeBackoffStrategy.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.core.retry; import java.time.Duration; import software.amazon.awssdk.core.retry.backoff.BackoffStrategy; /** * Test implementation of {@link BackoffStrategy} to wait a fixed time between retries */ public class FixedTimeBackoffStrategy implements BackoffStrategy { private final Duration fixedTimeDelay; public FixedTimeBackoffStrategy(Duration fixedTimeDelay) { this.fixedTimeDelay = fixedTimeDelay; } @Override public Duration computeDelayBeforeNextRetry(RetryPolicyContext context) { return this.fixedTimeDelay; } }
1,882
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/retry/RetryModeTest.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.core.retry; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collection; import java.util.concurrent.Callable; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.profiles.ProfileFileSystemSetting; import software.amazon.awssdk.testutils.EnvironmentVariableHelper; import software.amazon.awssdk.utils.Validate; @RunWith(Parameterized.class) public class RetryModeTest { private static final EnvironmentVariableHelper ENVIRONMENT_VARIABLE_HELPER = new EnvironmentVariableHelper(); @Parameterized.Parameter public TestData testData; @Parameterized.Parameters public static Collection<Object> data() { return Arrays.asList(new Object[] { // Test defaults new TestData(null, null, null, null, RetryMode.LEGACY), new TestData(null, null, "PropertyNotSet", null, RetryMode.LEGACY), // Test resolution new TestData("legacy", null, null, null, RetryMode.LEGACY), new TestData("standard", null, null, null, RetryMode.STANDARD), new TestData("adaptive", null, null, null, RetryMode.ADAPTIVE), new TestData("lEgAcY", null, null, null, RetryMode.LEGACY), new TestData("sTanDaRd", null, null, null, RetryMode.STANDARD), new TestData("aDaPtIvE", null, null, null, RetryMode.ADAPTIVE), // Test precedence new TestData("standard", "legacy", "PropertySetToLegacy", RetryMode.LEGACY, RetryMode.STANDARD), new TestData("standard", null, null, RetryMode.LEGACY, RetryMode.STANDARD), new TestData(null, "standard", "PropertySetToLegacy", RetryMode.LEGACY, RetryMode.STANDARD), new TestData(null, "standard", null, RetryMode.LEGACY, RetryMode.STANDARD), new TestData(null, null, "PropertySetToStandard", RetryMode.LEGACY, RetryMode.STANDARD), new TestData(null, null, null, RetryMode.STANDARD, RetryMode.STANDARD), // Test invalid values new TestData("wrongValue", null, null, null, IllegalStateException.class), new TestData(null, "wrongValue", null, null, IllegalStateException.class), new TestData(null, null, "PropertySetToUnsupportedValue", null, IllegalStateException.class), // Test capitalization standardization new TestData("sTaNdArD", null, null, null, RetryMode.STANDARD), new TestData(null, "sTaNdArD", null, null, RetryMode.STANDARD), new TestData(null, null, "PropertyMixedCase", null, RetryMode.STANDARD), }); } @Before @After public void methodSetup() { ENVIRONMENT_VARIABLE_HELPER.reset(); System.clearProperty(SdkSystemSetting.AWS_RETRY_MODE.property()); System.clearProperty(ProfileFileSystemSetting.AWS_PROFILE.property()); System.clearProperty(ProfileFileSystemSetting.AWS_CONFIG_FILE.property()); } @Test public void differentCombinationOfConfigs_shouldResolveCorrectly() throws Exception { if (testData.envVarValue != null) { ENVIRONMENT_VARIABLE_HELPER.set(SdkSystemSetting.AWS_RETRY_MODE.environmentVariable(), testData.envVarValue); } if (testData.systemProperty != null) { System.setProperty(SdkSystemSetting.AWS_RETRY_MODE.property(), testData.systemProperty); } if (testData.configFile != null) { String diskLocationForFile = diskLocationForConfig(testData.configFile); Validate.isTrue(Files.isReadable(Paths.get(diskLocationForFile)), diskLocationForFile + " is not readable."); System.setProperty(ProfileFileSystemSetting.AWS_PROFILE.property(), "default"); System.setProperty(ProfileFileSystemSetting.AWS_CONFIG_FILE.property(), diskLocationForFile); } Callable<RetryMode> result = RetryMode.resolver().defaultRetryMode(testData.defaultMode)::resolve; if (testData.expected instanceof Class<?>) { Class<?> expectedClassType = (Class<?>) testData.expected; assertThatThrownBy(result::call).isInstanceOf(expectedClassType); } else { assertThat(result.call()).isEqualTo(testData.expected); } } private String diskLocationForConfig(String configFileName) { return getClass().getResource(configFileName).getFile(); } private static class TestData { private final String envVarValue; private final String systemProperty; private final String configFile; private final RetryMode defaultMode; private final Object expected; TestData(String systemProperty, String envVarValue, String configFile, RetryMode defaultMode, Object expected) { this.envVarValue = envVarValue; this.systemProperty = systemProperty; this.configFile = configFile; this.defaultMode = defaultMode; this.expected = expected; } } }
1,883
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/retry/DefaultRetryConditionTest.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.core.retry; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.util.function.Consumer; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.exception.NonRetryableException; import software.amazon.awssdk.core.exception.RetryableException; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.core.retry.conditions.RetryCondition; public class DefaultRetryConditionTest { @Test public void retriesOnThrottlingExceptions() { assertTrue(shouldRetry(applyStatusCode(429))); } @Test public void retriesOnInternalError() { assertTrue(shouldRetry(applyStatusCode(500))); } @Test public void retriesOnBadGateway() { assertTrue(shouldRetry(applyStatusCode(502))); } @Test public void retriesOnServiceUnavailable() { assertTrue(shouldRetry(applyStatusCode(503))); } @Test public void retriesOnGatewayTimeout() { assertTrue(shouldRetry(applyStatusCode(504))); } @Test public void retriesOnIOException() { assertTrue(shouldRetry(b -> b.exception(SdkClientException.builder().message("IO").cause(new IOException()).build()))); } @Test public void retriesOnRetryableException() { assertTrue(shouldRetry(b -> b.exception(RetryableException.builder().message("this is retryable").build()))); } @Test public void doesNotRetryOnNonRetryableException() { assertFalse(shouldRetry(b -> b.exception(NonRetryableException.builder().message("this is NOT retryable").build()))); } @Test public void doesNotRetryOnNonRetryableStatusCode() { assertFalse(shouldRetry(applyStatusCode(404))); } private boolean shouldRetry(Consumer<RetryPolicyContext.Builder> builder) { return RetryCondition.defaultRetryCondition().shouldRetry(RetryPolicyContext.builder() .applyMutation(builder) .build()); } private Consumer<RetryPolicyContext.Builder> applyStatusCode(Integer statusCode) { SdkServiceException exception = SdkServiceException.builder().statusCode(statusCode).build(); return b -> b.exception(exception) .httpStatusCode(statusCode); } }
1,884
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/retry/MaxNumberOfRetriesConditionTest.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.core.retry; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.retry.conditions.MaxNumberOfRetriesCondition; public class MaxNumberOfRetriesConditionTest { @Test public void positiveMaxRetries_OneMoreAttemptToMax_ReturnsTrue() { assertTrue(MaxNumberOfRetriesCondition.create(3).shouldRetry(RetryPolicyContexts.withRetriesAttempted(2))); } @Test public void positiveMaxRetries_AtMaxAttempts_ReturnsFalse() { assertFalse(MaxNumberOfRetriesCondition.create(3).shouldRetry(RetryPolicyContexts.withRetriesAttempted(3))); } @Test public void positiveMaxRetries_PastMaxAttempts_ReturnsFalse() { assertFalse(MaxNumberOfRetriesCondition.create(3).shouldRetry(RetryPolicyContexts.withRetriesAttempted(4))); } }
1,885
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/retry/FixedDelayBackoffStrategyTest.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.core.retry; import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.Duration; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.retry.backoff.FixedDelayBackoffStrategy; public class FixedDelayBackoffStrategyTest { @Test public void positiveBackoff_ReturnsFixedBackoffOnDelay() { long delay = FixedDelayBackoffStrategy.create(Duration.ofMillis(100)).computeDelayBeforeNextRetry(RetryPolicyContexts.EMPTY) .toMillis(); assertEquals(100, delay); } }
1,886
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/retry/RetryPolicyMaxRetriesTest.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.core.retry; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collection; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.profiles.ProfileFileSystemSetting; import software.amazon.awssdk.testutils.EnvironmentVariableHelper; import software.amazon.awssdk.utils.Validate; @RunWith(Parameterized.class) public class RetryPolicyMaxRetriesTest { private static final EnvironmentVariableHelper ENVIRONMENT_VARIABLE_HELPER = new EnvironmentVariableHelper(); @Parameterized.Parameter public TestData testData; @Parameterized.Parameters public static Collection<Object> data() { return Arrays.asList(new Object[] { // Test defaults new TestData(null, null, null, null, null, 3), new TestData(null, null, null, null, "PropertyNotSet", 3), // Test precedence new TestData("9", "2", "standard", "standard", "PropertySetToStandard", 8), new TestData(null, "9", "standard", "standard", "PropertySetToStandard", 8), new TestData(null, null, "standard", "standard", "PropertySetToStandard", 2), new TestData(null, null, null, "standard", "PropertySetToStandard", 2), new TestData(null, null, null, null, "PropertySetToStandard", 2), // Test invalid values new TestData("wrongValue", null, null, null, null, null), new TestData(null, "wrongValue", null, null, null, null), new TestData(null, null, "wrongValue", null, null, null), new TestData(null, null, null, "wrongValue", null, null), new TestData(null, null, null, null, "PropertySetToUnsupportedValue", null), }); } @BeforeClass public static void classSetup() { // If this caches any values, make sure it's cached with the default (non-modified) configuration. RetryPolicy.defaultRetryPolicy(); } @Before @After public void methodSetup() { ENVIRONMENT_VARIABLE_HELPER.reset(); System.clearProperty(SdkSystemSetting.AWS_MAX_ATTEMPTS.property()); System.clearProperty(SdkSystemSetting.AWS_RETRY_MODE.property()); System.clearProperty(ProfileFileSystemSetting.AWS_PROFILE.property()); System.clearProperty(ProfileFileSystemSetting.AWS_CONFIG_FILE.property()); } @Test public void differentCombinationOfConfigs_shouldResolveCorrectly() { if (testData.attemptCountEnvVarValue != null) { ENVIRONMENT_VARIABLE_HELPER.set(SdkSystemSetting.AWS_MAX_ATTEMPTS.environmentVariable(), testData.attemptCountEnvVarValue); } if (testData.attemptCountSystemProperty != null) { System.setProperty(SdkSystemSetting.AWS_MAX_ATTEMPTS.property(), testData.attemptCountSystemProperty); } if (testData.envVarValue != null) { ENVIRONMENT_VARIABLE_HELPER.set(SdkSystemSetting.AWS_RETRY_MODE.environmentVariable(), testData.envVarValue); } if (testData.systemProperty != null) { System.setProperty(SdkSystemSetting.AWS_RETRY_MODE.property(), testData.systemProperty); } if (testData.configFile != null) { String diskLocationForFile = diskLocationForConfig(testData.configFile); Validate.isTrue(Files.isReadable(Paths.get(diskLocationForFile)), diskLocationForFile + " is not readable."); System.setProperty(ProfileFileSystemSetting.AWS_PROFILE.property(), "default"); System.setProperty(ProfileFileSystemSetting.AWS_CONFIG_FILE.property(), diskLocationForFile); } if (testData.expected == null) { assertThatThrownBy(() -> RetryPolicy.forRetryMode(RetryMode.defaultRetryMode())).isInstanceOf(RuntimeException.class); } else { assertThat(RetryPolicy.forRetryMode(RetryMode.defaultRetryMode()).numRetries()).isEqualTo(testData.expected); } } private String diskLocationForConfig(String configFileName) { return getClass().getResource(configFileName).getFile(); } private static class TestData { private final String attemptCountSystemProperty; private final String attemptCountEnvVarValue; private final String envVarValue; private final String systemProperty; private final String configFile; private final Integer expected; TestData(String attemptCountSystemProperty, String attemptCountEnvVarValue, String retryModeSystemProperty, String retryModeEnvVarValue, String configFile, Integer expected) { this.attemptCountSystemProperty = attemptCountSystemProperty; this.attemptCountEnvVarValue = attemptCountEnvVarValue; this.envVarValue = retryModeEnvVarValue; this.systemProperty = retryModeSystemProperty; this.configFile = configFile; this.expected = expected; } } }
1,887
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/retry/OrRetryConditionTest.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.core.retry; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import org.junit.Before; 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.retry.conditions.OrRetryCondition; import software.amazon.awssdk.core.retry.conditions.RetryCondition; @RunWith(MockitoJUnitRunner.class) public class OrRetryConditionTest { @Mock private RetryCondition conditionOne; @Mock private RetryCondition conditionTwo; private RetryCondition orCondition; @Before public void setup() { this.orCondition = OrRetryCondition.create(conditionOne, conditionTwo); } @Test public void allFalseConditions_ReturnsFalse() { assertFalse(orCondition.shouldRetry(RetryPolicyContexts.EMPTY)); } @Test public void firstConditionIsTrue_ReturnsTrue() { when(conditionOne.shouldRetry(any(RetryPolicyContext.class))) .thenReturn(true); assertTrue(orCondition.shouldRetry(RetryPolicyContexts.EMPTY)); } @Test public void secondConditionIsTrue_ReturnsTrue() { when(conditionTwo.shouldRetry(any(RetryPolicyContext.class))) .thenReturn(true); assertTrue(orCondition.shouldRetry(RetryPolicyContexts.EMPTY)); } @Test public void noConditions_ReturnsFalse() { assertFalse(OrRetryCondition.create().shouldRetry(RetryPolicyContexts.EMPTY)); } @Test public void singleConditionThatReturnsTrue_ReturnsTrue() { when(conditionOne.shouldRetry(RetryPolicyContexts.EMPTY)) .thenReturn(true); assertTrue(OrRetryCondition.create(conditionOne).shouldRetry(RetryPolicyContexts.EMPTY)); } @Test public void singleConditionThatReturnsFalse_ReturnsFalse() { when(conditionOne.shouldRetry(RetryPolicyContexts.EMPTY)) .thenReturn(false); assertFalse(OrRetryCondition.create(conditionOne).shouldRetry(RetryPolicyContexts.EMPTY)); } @Test public void conditionsAreEvaluatedInOrder() { int numConditions = 1000; int firstTrueCondition = 500; RetryCondition[] conditions = new RetryCondition[numConditions]; for (int i = 0; i < numConditions; ++i) { RetryCondition mock = Mockito.mock(RetryCondition.class); when(mock.shouldRetry(RetryPolicyContexts.EMPTY)).thenReturn(i == firstTrueCondition); conditions[i] = mock; } assertTrue(OrRetryCondition.create(conditions).shouldRetry(RetryPolicyContexts.EMPTY)); for (int i = 0; i < numConditions; ++i) { int timesExpected = i <= firstTrueCondition ? 1 : 0; Mockito.verify(conditions[i], times(timesExpected)).shouldRetry(RetryPolicyContexts.EMPTY); } } }
1,888
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/retry/RetryOnStatusCodeConditionTest.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.core.retry; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import com.google.common.collect.Sets; import java.util.Collections; import java.util.Set; import org.junit.Test; import software.amazon.awssdk.core.retry.conditions.RetryCondition; import software.amazon.awssdk.core.retry.conditions.RetryOnStatusCodeCondition; public class RetryOnStatusCodeConditionTest { private final RetryCondition condition = RetryOnStatusCodeCondition.create(Sets.newHashSet(404, 500, 513)); @Test public void retryableStatusCode_ReturnsTrue() { assertTrue(condition.shouldRetry(RetryPolicyContexts.withStatusCode(404))); } @Test public void nonRetryableStatusCode_ReturnsTrue() { assertFalse(condition.shouldRetry(RetryPolicyContexts.withStatusCode(400))); } @Test public void noStatusCodeInContext_ReturnFalse() { assertFalse(condition.shouldRetry(RetryPolicyContexts.withStatusCode(null))); } @Test public void noStatusCodesInList_ReturnsFalse() { final RetryCondition noStatusCodes = RetryOnStatusCodeCondition.create(Collections.emptySet()); assertFalse(noStatusCodes.shouldRetry(RetryPolicyContexts.withStatusCode(404))); } @Test(expected = NullPointerException.class) public void nullListOfStatusCodes_ThrowsException() { Set<Integer> nullSet = null; RetryOnStatusCodeCondition.create(nullSet); } }
1,889
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/retry/RetryPolicyContexts.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.core.retry; import software.amazon.awssdk.core.exception.SdkException; /** * Precanned instances of {@link RetryPolicyContext} and factory methods for creating contexts. */ public class RetryPolicyContexts { /** * Empty context object. */ public static final RetryPolicyContext EMPTY = RetryPolicyContext.builder().build(); public static RetryPolicyContext withException(SdkException e) { return RetryPolicyContext.builder() .exception(e) .build(); } public static RetryPolicyContext withStatusCode(Integer httpStatusCode) { return RetryPolicyContext.builder() .httpStatusCode(httpStatusCode) .build(); } public static RetryPolicyContext withRetriesAttempted(int retriesAttempted) { return RetryPolicyContext.builder() .retriesAttempted(retriesAttempted) .build(); } }
1,890
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/retry/RetryPolicyContextTest.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.core.retry; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.http.NoopTestRequest; import software.amazon.awssdk.http.SdkHttpFullRequest; import utils.ValidSdkObjects; public class RetryPolicyContextTest { @Test public void totalRequests_IsOneMoreThanRetriesAttempted() { assertEquals(4, RetryPolicyContexts.withRetriesAttempted(3).totalRequests()); } @Test public void nullHttpStatusCodeAllowed() { assertNull(RetryPolicyContexts.withStatusCode(null).httpStatusCode()); } @Test public void nullExceptionAllowed() { assertNull(RetryPolicyContexts.withException(null).exception()); } @Test public void buildFully() { final SdkRequest origRequest = NoopTestRequest.builder().build(); final SdkHttpFullRequest request = ValidSdkObjects.sdkHttpFullRequest().build(); final SdkClientException exception = SdkClientException.builder().message("boom").build(); final RetryPolicyContext context = RetryPolicyContext.builder() .retriesAttempted(3) .httpStatusCode(400) .request(request) .exception(exception) .originalRequest(origRequest) .build(); assertEquals(3, context.retriesAttempted()); assertEquals(Integer.valueOf(400), context.httpStatusCode()); assertEquals(request, context.request()); assertEquals(exception, context.exception()); assertEquals(origRequest, context.originalRequest()); } }
1,891
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/retry/RetryPolicyTest.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.core.retry; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.verify; import java.time.Duration; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.core.retry.backoff.BackoffStrategy; import software.amazon.awssdk.core.retry.backoff.EqualJitterBackoffStrategy; import software.amazon.awssdk.core.retry.backoff.FullJitterBackoffStrategy; import software.amazon.awssdk.core.retry.conditions.RetryCondition; @RunWith(MockitoJUnitRunner.class) public class RetryPolicyTest { @Mock private RetryCondition retryCondition; @Mock private BackoffStrategy backoffStrategy; @Mock private BackoffStrategy throttlingBackoffStrategy; @Test public void nullConditionProvided_useDefault() { RetryPolicy policy = RetryPolicy.builder().build(); RetryPolicy defaultRetryPolicy = RetryPolicy.defaultRetryPolicy(); assertThat(policy).isEqualTo(defaultRetryPolicy); assertThat(policy.retryCondition()).isEqualTo(defaultRetryPolicy.retryCondition()); assertThat(policy.backoffStrategy()).isEqualTo(BackoffStrategy.defaultStrategy()); assertThat(policy.throttlingBackoffStrategy()).isEqualTo(BackoffStrategy.defaultThrottlingStrategy()); } @Test public void shouldRetry_DelegatesToRetryCondition() { RetryPolicy policy = RetryPolicy.builder().retryCondition(retryCondition).backoffStrategy(backoffStrategy).build(); policy.retryCondition().shouldRetry(RetryPolicyContexts.EMPTY); verify(retryCondition).shouldRetry(RetryPolicyContexts.EMPTY); } @Test public void delay_DelegatesToBackoffStrategy() { RetryPolicy policy = RetryPolicy.builder().retryCondition(retryCondition).backoffStrategy(backoffStrategy).build(); policy.backoffStrategy().computeDelayBeforeNextRetry(RetryPolicyContexts.EMPTY); verify(backoffStrategy).computeDelayBeforeNextRetry(RetryPolicyContexts.EMPTY); } @Test public void throttlingDelay_delegatesToThrottlingBackoffStrategy() { RetryPolicy policy = RetryPolicy.builder().throttlingBackoffStrategy(throttlingBackoffStrategy).build(); policy.throttlingBackoffStrategy().computeDelayBeforeNextRetry(RetryPolicyContexts.EMPTY); verify(throttlingBackoffStrategy).computeDelayBeforeNextRetry(RetryPolicyContexts.EMPTY); } @Test public void nonRetryPolicy_shouldUseNullCondition() { RetryPolicy noneRetry = RetryPolicy.none(); assertThat(noneRetry.retryCondition().shouldRetry(RetryPolicyContext.builder().build())).isFalse(); assertThat(noneRetry.numRetries()).isZero(); assertThat(noneRetry.backoffStrategy()).isEqualTo(BackoffStrategy.none()); assertThat(noneRetry.throttlingBackoffStrategy()).isEqualTo(BackoffStrategy.none()); } @Test public void nonRetryMode_shouldUseDefaultRetryMode() { RetryPolicy policy = RetryPolicy.builder().build(); assertThat(policy.retryMode().toString()).isEqualTo("LEGACY"); } @Test public void nullRetryMode_shouldThrowNullPointerException() { assertThatThrownBy(() -> RetryPolicy.builder(null).build()) .isInstanceOf(NullPointerException.class) .hasMessageContaining("retry mode cannot be set as null"); } @Test public void maxRetriesFromRetryModeIsCorrect() { assertThat(RetryPolicy.forRetryMode(RetryMode.LEGACY).numRetries()).isEqualTo(3); assertThat(RetryPolicy.forRetryMode(RetryMode.STANDARD).numRetries()).isEqualTo(2); } @Test public void maxRetriesFromDefaultRetryModeIsCorrect() { switch (RetryMode.defaultRetryMode()) { case LEGACY: assertThat(RetryPolicy.defaultRetryPolicy().numRetries()).isEqualTo(3); assertThat(RetryPolicy.builder().build().numRetries()).isEqualTo(3); break; case STANDARD: assertThat(RetryPolicy.defaultRetryPolicy().numRetries()).isEqualTo(2); assertThat(RetryPolicy.builder().build().numRetries()).isEqualTo(2); break; default: Assert.fail(); } } @Test public void legacyRetryMode_shouldUseFullJitterAndEqualJitter() { RetryPolicy legacyRetryPolicy = RetryPolicy.forRetryMode(RetryMode.LEGACY); assertThat(legacyRetryPolicy.backoffStrategy()).isInstanceOf(FullJitterBackoffStrategy.class); FullJitterBackoffStrategy backoffStrategy = (FullJitterBackoffStrategy) legacyRetryPolicy.backoffStrategy(); assertThat(backoffStrategy.toBuilder().baseDelay()).isEqualTo(Duration.ofMillis(100)); assertThat(backoffStrategy.toBuilder().maxBackoffTime()).isEqualTo(Duration.ofSeconds(20)); assertThat(legacyRetryPolicy.throttlingBackoffStrategy()).isInstanceOf(EqualJitterBackoffStrategy.class); EqualJitterBackoffStrategy throttlingBackoffStrategy = (EqualJitterBackoffStrategy) legacyRetryPolicy.throttlingBackoffStrategy(); assertThat(throttlingBackoffStrategy.toBuilder().baseDelay()).isEqualTo(Duration.ofMillis(500)); assertThat(throttlingBackoffStrategy.toBuilder().maxBackoffTime()).isEqualTo(Duration.ofSeconds(20)); } @Test public void standardRetryMode_shouldUseFullJitterOnly() { RetryPolicy standardRetryPolicy = RetryPolicy.forRetryMode(RetryMode.STANDARD); assertThat(standardRetryPolicy.backoffStrategy()).isInstanceOf(FullJitterBackoffStrategy.class); FullJitterBackoffStrategy backoffStrategy = (FullJitterBackoffStrategy) standardRetryPolicy.backoffStrategy(); assertThat(backoffStrategy.toBuilder().baseDelay()).isEqualTo(Duration.ofMillis(100)); assertThat(backoffStrategy.toBuilder().maxBackoffTime()).isEqualTo(Duration.ofSeconds(20)); assertThat(standardRetryPolicy.throttlingBackoffStrategy()).isInstanceOf(FullJitterBackoffStrategy.class); FullJitterBackoffStrategy throttlingBackoffStrategy = (FullJitterBackoffStrategy) standardRetryPolicy.throttlingBackoffStrategy(); assertThat(throttlingBackoffStrategy.toBuilder().baseDelay()).isEqualTo(Duration.ofSeconds(1)); assertThat(throttlingBackoffStrategy.toBuilder().maxBackoffTime()).isEqualTo(Duration.ofSeconds(20)); } @Test public void adaptiveRetryMode_shouldUseFullJitterOnly() { RetryPolicy standardRetryPolicy = RetryPolicy.forRetryMode(RetryMode.ADAPTIVE); assertThat(standardRetryPolicy.backoffStrategy()).isInstanceOf(FullJitterBackoffStrategy.class); FullJitterBackoffStrategy backoffStrategy = (FullJitterBackoffStrategy) standardRetryPolicy.backoffStrategy(); assertThat(backoffStrategy.toBuilder().baseDelay()).isEqualTo(Duration.ofMillis(100)); assertThat(backoffStrategy.toBuilder().maxBackoffTime()).isEqualTo(Duration.ofSeconds(20)); assertThat(standardRetryPolicy.throttlingBackoffStrategy()).isInstanceOf(FullJitterBackoffStrategy.class); FullJitterBackoffStrategy throttlingBackoffStrategy = (FullJitterBackoffStrategy) standardRetryPolicy.throttlingBackoffStrategy(); assertThat(throttlingBackoffStrategy.toBuilder().baseDelay()).isEqualTo(Duration.ofSeconds(1)); assertThat(throttlingBackoffStrategy.toBuilder().maxBackoffTime()).isEqualTo(Duration.ofSeconds(20)); } @Test public void fastFailRateLimitingConfigured_retryModeNotAdaptive_throws() { assertThatThrownBy(() -> RetryPolicy.builder(RetryMode.STANDARD).fastFailRateLimiting(true).build()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("only valid for the ADAPTIVE retry mode"); } @Test public void fastFailRateLimitingConfigured_retryModeAdaptive_doesNotThrow() { RetryPolicy.builder(RetryMode.ADAPTIVE).fastFailRateLimiting(true).build(); } @Test public void hashCodeDoesNotThrow() { RetryPolicy.defaultRetryPolicy().hashCode(); } }
1,892
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/retry
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/retry/backoff/FullJitterBackoffStrategyTest.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.core.retry.backoff; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.AdditionalAnswers.returnsFirstArg; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.mockito.Mockito.withSettings; import java.time.Duration; import java.util.Arrays; import java.util.Collection; import java.util.Random; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; import org.mockito.Mock; import org.mockito.stubbing.Answer; import software.amazon.awssdk.core.retry.RetryMode; import software.amazon.awssdk.core.retry.RetryPolicyContext; @RunWith(Parameterized.class) public class FullJitterBackoffStrategyTest { @Parameters public static Collection<TestCase> parameters() throws Exception { return Arrays.asList( new TestCase().backoffStrategy(BackoffStrategy.defaultStrategy(RetryMode.STANDARD)) .retriesAttempted(0) .expectedMaxDelay(Duration.ofMillis(100)) .expectedMedDelay(Duration.ofMillis(50)) .expectedMinDelay(Duration.ofMillis(1)), new TestCase().backoffStrategy(BackoffStrategy.defaultStrategy(RetryMode.STANDARD)) .retriesAttempted(1) .expectedMaxDelay(Duration.ofMillis(200)) .expectedMedDelay(Duration.ofMillis(100)) .expectedMinDelay(Duration.ofMillis(1)), new TestCase().backoffStrategy(BackoffStrategy.defaultStrategy(RetryMode.STANDARD)) .retriesAttempted(2) .expectedMaxDelay(Duration.ofMillis(400)) .expectedMedDelay(Duration.ofMillis(200)) .expectedMinDelay(Duration.ofMillis(1)), new TestCase().backoffStrategy(BackoffStrategy.defaultStrategy(RetryMode.STANDARD)) .retriesAttempted(3) .expectedMaxDelay(Duration.ofMillis(800)) .expectedMedDelay(Duration.ofMillis(400)) .expectedMinDelay(Duration.ofMillis(1)), new TestCase().backoffStrategy(BackoffStrategy.defaultStrategy(RetryMode.STANDARD)) .retriesAttempted(4) .expectedMaxDelay(Duration.ofMillis(1600)) .expectedMedDelay(Duration.ofMillis(800)) .expectedMinDelay(Duration.ofMillis(1)), new TestCase().backoffStrategy(BackoffStrategy.defaultStrategy(RetryMode.STANDARD)) .retriesAttempted(5) .expectedMaxDelay(Duration.ofMillis(3200)) .expectedMedDelay(Duration.ofMillis(1600)) .expectedMinDelay(Duration.ofMillis(1)), new TestCase().backoffStrategy(BackoffStrategy.defaultStrategy(RetryMode.STANDARD)) .retriesAttempted(100) .expectedMaxDelay(Duration.ofSeconds(20)) .expectedMedDelay(Duration.ofSeconds(10)) .expectedMinDelay(Duration.ofMillis(1)) ); } @Parameter public TestCase testCase; @Mock private Random mockRandom = mock(Random.class, withSettings().withoutAnnotations()); @Before public void setUp() throws Exception { testCase.backoffStrategy = injectMockRandom(testCase.backoffStrategy); } @Test public void testMaxDelay() { mockMaxRandom(); test(testCase.backoffStrategy, testCase.retriesAttempted, testCase.expectedMaxDelay); } @Test public void testMedDelay() { mockMediumRandom(); test(testCase.backoffStrategy, testCase.retriesAttempted, testCase.expectedMedDelay); } @Test public void testMinDelay() { mockMinRandom(); test(testCase.backoffStrategy, testCase.retriesAttempted, testCase.expectedMinDelay); } private static void test(BackoffStrategy backoffStrategy, int retriesAttempted, Duration expectedDelay) { RetryPolicyContext context = RetryPolicyContext.builder() .retriesAttempted(retriesAttempted) .build(); Duration computedDelay = backoffStrategy.computeDelayBeforeNextRetry(context); assertThat(computedDelay).isEqualTo(expectedDelay); } private FullJitterBackoffStrategy injectMockRandom(BackoffStrategy strategy) { FullJitterBackoffStrategy.Builder builder = ((FullJitterBackoffStrategy) strategy).toBuilder(); return new FullJitterBackoffStrategy(builder.baseDelay(), builder.maxBackoffTime(), mockRandom); } private void mockMaxRandom() { when(mockRandom.nextInt(anyInt())).then((Answer<Integer>) invocationOnMock -> { Integer firstArg = (Integer) returnsFirstArg().answer(invocationOnMock); return firstArg - 1; }); } private void mockMinRandom() { when(mockRandom.nextInt(anyInt())).then((Answer<Integer>) invocationOnMock -> { return 0; }); } private void mockMediumRandom() { when(mockRandom.nextInt(anyInt())).then((Answer<Integer>) invocationOnMock -> { Integer firstArg = (Integer) returnsFirstArg().answer(invocationOnMock); return firstArg / 2 - 1; }); } private static class TestCase { private BackoffStrategy backoffStrategy; private int retriesAttempted; private Duration expectedMinDelay; private Duration expectedMedDelay; private Duration expectedMaxDelay; public TestCase backoffStrategy(BackoffStrategy backoffStrategy) { this.backoffStrategy = backoffStrategy; return this; } public TestCase retriesAttempted(int retriesAttempted) { this.retriesAttempted = retriesAttempted; return this; } public TestCase expectedMinDelay(Duration expectedMinDelay) { this.expectedMinDelay = expectedMinDelay; return this; } public TestCase expectedMedDelay(Duration expectedMedDelay) { this.expectedMedDelay = expectedMedDelay; return this; } public TestCase expectedMaxDelay(Duration expectedMaxDelay) { this.expectedMaxDelay = expectedMaxDelay; return this; } } }
1,893
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/retry
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/retry/backoff/EqualJitterBackoffStrategyTest.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.core.retry.backoff; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.mockito.Mockito.withSettings; import static org.testng.Assert.assertThrows; import java.time.Duration; import java.util.Random; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockSettings; import software.amazon.awssdk.core.retry.RetryPolicyContext; public class EqualJitterBackoffStrategyTest { private static final int RANDOM_RESULT = 12345; private static final Duration FIVE_DAYS = Duration.ofDays(5); private static final Duration MAX_DURATION = Duration.ofSeconds(Long.MAX_VALUE); private static final Duration ONE_SECOND = Duration.ofSeconds(1); private static final Duration ONE_NANO_SECOND = Duration.ofNanos(1); private static final int NANO_IN_MILLISECONDS = 1_000_000; private static final Duration NEGATIVE_ONE_SECOND = Duration.ofSeconds(-1); @Mock private Random mockRandom = mock(Random.class, withSettings().withoutAnnotations()); @Test public void exponentialDelayOverflowWithMaxBackoffTest() { test(FIVE_DAYS, MAX_DURATION, 3, Integer.MAX_VALUE); } @Test public void exponentialDelayOverflowWithMaxBaseDelayTest() { test(MAX_DURATION, MAX_DURATION, 1, Integer.MAX_VALUE); } @Test public void maxBaseDelayShortBackoffTest() { test(MAX_DURATION, ONE_SECOND, 1, (int) ONE_SECOND.toMillis()); } @Test public void normalConditionTest() { test(ONE_SECOND, MAX_DURATION, 10, (1 << 10) * (int) ONE_SECOND.toMillis()); } @Test public void tinyBackoffNormalRetriesTest() { test(MAX_DURATION, ONE_NANO_SECOND, 10, 0); } @Test public void tinyBaseDelayNormalRetriesTest() { test(ONE_NANO_SECOND, MAX_DURATION, 30, (int) (1L << 30) / NANO_IN_MILLISECONDS); } @Test public void tinyBaseDelayExtraRetriesTest() { test(ONE_NANO_SECOND, MAX_DURATION, 100, (int) (1L << 30) / NANO_IN_MILLISECONDS); // RETRIES_ATTEMPTED_CEILING == 30 } @Test public void exponentialDelayOverflowWithExtraRetriesTest() { test(MAX_DURATION, MAX_DURATION, 100, Integer.MAX_VALUE); } @Test public void tinyBaseDelayUnderflowTest() { test(ONE_NANO_SECOND, MAX_DURATION, 0, 0); } @Test public void negativeBaseDelayTest() { assertThrows(IllegalArgumentException.class, () -> test(NEGATIVE_ONE_SECOND, MAX_DURATION, 1, 0)); } @Test public void negativeBackoffTest() { assertThrows(IllegalArgumentException.class, () -> test(ONE_SECOND, NEGATIVE_ONE_SECOND, 1, 0)); } private void test(final Duration baseDelay, final Duration maxBackoffTime, final int retriesAttempted, final int expectedCeilingMillis) { final BackoffStrategy backoffStrategy = new EqualJitterBackoffStrategy(baseDelay, maxBackoffTime, mockRandom); when(mockRandom.nextInt(expectedCeilingMillis /2 + 1)).thenReturn(RANDOM_RESULT); assertThat(backoffStrategy.computeDelayBeforeNextRetry(toRetryContext(retriesAttempted)), is(Duration.ofMillis(expectedCeilingMillis / 2 + RANDOM_RESULT))); } private static RetryPolicyContext toRetryContext(final int retriesAttempted) { return RetryPolicyContext.builder().retriesAttempted(retriesAttempted).build(); } }
1,894
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/retry
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/retry/conditions/TokenBucketRetryConditionTest.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.core.retry.conditions; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.fail; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.exception.SdkException; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.retry.RetryPolicyContext; public class TokenBucketRetryConditionTest { private static final SdkException EXCEPTION = SdkClientException.create(""); private static final SdkException EXCEPTION_2 = SdkClientException.create(""); @Test public void maximumTokensCannotBeExceeded() { TokenBucketRetryCondition condition = create(3, e -> 1); for (int i = 1; i < 10; ++i) { condition.requestSucceeded(context(null)); assertThat(condition.tokensAvailable()).isEqualTo(3); } } @Test public void releasingMoreCapacityThanAvailableSetsCapacityToMax() { ExecutionAttributes attributes = new ExecutionAttributes(); TokenBucketRetryCondition condition = create(11, e -> e == EXCEPTION ? 1 : 3); assertThat(condition.shouldRetry(context(EXCEPTION, attributes))).isTrue(); assertThat(condition.tokensAvailable()).isEqualTo(10); assertThat(condition.shouldRetry(context(EXCEPTION_2, attributes))).isTrue(); assertThat(condition.tokensAvailable()).isEqualTo(7); condition.requestSucceeded(context(EXCEPTION_2, attributes)); assertThat(condition.tokensAvailable()).isEqualTo(10); condition.requestSucceeded(context(EXCEPTION_2, attributes)); assertThat(condition.tokensAvailable()).isEqualTo(11); } @Test public void nonFirstAttemptsAreNotFree() { TokenBucketRetryCondition condition = create(2, e -> 1); assertThat(condition.shouldRetry(context(EXCEPTION))).isTrue(); assertThat(condition.tokensAvailable()).isEqualTo(1); assertThat(condition.shouldRetry(context(EXCEPTION))).isTrue(); assertThat(condition.tokensAvailable()).isEqualTo(0); assertThat(condition.shouldRetry(context(EXCEPTION))).isFalse(); assertThat(condition.tokensAvailable()).isEqualTo(0); } @Test public void exceptionCostIsHonored() { // EXCEPTION costs 1, anything else costs 10 TokenBucketRetryCondition condition = create(20, e -> e == EXCEPTION ? 1 : 10); assertThat(condition.shouldRetry(context(EXCEPTION))).isTrue(); assertThat(condition.tokensAvailable()).isEqualTo(19); assertThat(condition.shouldRetry(context(EXCEPTION_2))).isTrue(); assertThat(condition.tokensAvailable()).isEqualTo(9); assertThat(condition.shouldRetry(context(EXCEPTION_2))).isFalse(); assertThat(condition.tokensAvailable()).isEqualTo(9); assertThat(condition.shouldRetry(context(EXCEPTION))).isTrue(); assertThat(condition.tokensAvailable()).isEqualTo(8); } @Test public void successReleasesAcquiredCost() { ExecutionAttributes attributes = new ExecutionAttributes(); TokenBucketRetryCondition condition = create(20, e -> 10); assertThat(condition.shouldRetry(context(EXCEPTION, attributes))).isTrue(); assertThat(condition.tokensAvailable()).isEqualTo(10); condition.requestSucceeded(context(EXCEPTION, attributes)); assertThat(condition.tokensAvailable()).isEqualTo(20); } @Test public void firstRequestSuccessReleasesOne() { TokenBucketRetryCondition condition = create(20, e -> 10); assertThat(condition.shouldRetry(context(null))).isTrue(); assertThat(condition.tokensAvailable()).isEqualTo(10); condition.requestSucceeded(context(null)); assertThat(condition.tokensAvailable()).isEqualTo(11); condition.requestSucceeded(context(null)); assertThat(condition.tokensAvailable()).isEqualTo(12); } @Test public void conditionSeemsToBeThreadSafe() throws InterruptedException { int bucketSize = 5; TokenBucketRetryCondition condition = create(bucketSize, e -> 1); AtomicInteger concurrentCalls = new AtomicInteger(0); AtomicBoolean failure = new AtomicBoolean(false); int parallelism = bucketSize * 2; ExecutorService executor = Executors.newFixedThreadPool(parallelism); for (int i = 0; i < parallelism; ++i) { executor.submit(() -> { try { for (int j = 0; j < 1000; ++j) { ExecutionAttributes attributes = new ExecutionAttributes(); if (condition.shouldRetry(context(EXCEPTION, attributes))) { int calls = concurrentCalls.addAndGet(1); if (calls > bucketSize) { failure.set(true); } Thread.sleep(1); concurrentCalls.addAndGet(-1); condition.requestSucceeded(context(EXCEPTION, attributes)); } else { Thread.sleep(1); } } } catch (Throwable t) { t.printStackTrace(); failure.set(true); } }); // Stagger the threads a bit. Thread.sleep(1); } executor.shutdown(); if (!executor.awaitTermination(1, TimeUnit.MINUTES)) { fail(); } assertThat(failure.get()).isFalse(); } private RetryPolicyContext context(SdkException lastException) { return RetryPolicyContext.builder() .executionAttributes(new ExecutionAttributes()) .exception(lastException) .build(); } private RetryPolicyContext context(SdkException lastException, ExecutionAttributes attributes) { return RetryPolicyContext.builder() .executionAttributes(attributes) .exception(lastException) .build(); } private TokenBucketRetryCondition create(int size, TokenBucketExceptionCostFunction function) { return TokenBucketRetryCondition.builder() .tokenBucketSize(size) .exceptionCostFunction(function) .build(); } }
1,895
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/util/DefaultSdkAutoConstructMapTest.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.core.util; import static org.assertj.core.api.Assertions.assertThat; import java.util.HashMap; import org.junit.jupiter.api.Test; public class DefaultSdkAutoConstructMapTest { private static final DefaultSdkAutoConstructMap<String, String> AUTO_CONSTRUCT_MAP = DefaultSdkAutoConstructMap.getInstance(); @Test public void equal_emptyMap() { assertThat(AUTO_CONSTRUCT_MAP.equals(new HashMap<>())).isTrue(); } @Test public void hashCode_sameAsEmptyMap() { assertThat(AUTO_CONSTRUCT_MAP.hashCode()).isEqualTo(new HashMap<>().hashCode()); // The hashCode is defined by the Map interface to be the hashCodes of // all the entries in the Map, so this should be 0. assertThat(AUTO_CONSTRUCT_MAP.hashCode()).isEqualTo(0); } @Test public void toString_emptyMap() { assertThat(AUTO_CONSTRUCT_MAP.toString()).isEqualTo("{}"); } }
1,896
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/util/IdempotentUtilsTest.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.core.util; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import org.junit.jupiter.api.Test; public class IdempotentUtilsTest { @Test public void resolveString_returns_givenString_when_nonnullString_is_passed() { String idempotencyToken = "120c7d4a-e982-4323-a53e-28989a0a9f26"; assertEquals(idempotencyToken, IdempotentUtils.resolveString(idempotencyToken)); } @Test public void resolveString_returns_emptyString_when_emptyString_is_passed() { String idempotencyToken = ""; assertEquals(idempotencyToken, IdempotentUtils.resolveString(idempotencyToken)); } @Test public void resolveString_returns_newUniqueToken_when_nullString_is_passed() { assertNotNull(IdempotentUtils.resolveString(null)); } }
1,897
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/util/Crc32ChecksumInputStreamTest.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.core.util; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.zip.CRC32; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.internal.util.Crc32ChecksumCalculatingInputStream; /** * Test CRC32ChecksumInputStream can calculate CRC32 checksum correctly. */ public class Crc32ChecksumInputStreamTest { private static final String TEST_DATA = "Jason, Yifei, Zach"; @Test public void testCrc32Checksum() throws IOException { CRC32 crc32 = new CRC32(); crc32.update(TEST_DATA.getBytes()); long expectedCRC32Checksum = crc32.getValue(); Crc32ChecksumCalculatingInputStream crc32InputStream = new Crc32ChecksumCalculatingInputStream(new ByteArrayInputStream(TEST_DATA.getBytes())); while (crc32InputStream.read() != -1) { ; } assertEquals(expectedCRC32Checksum, crc32InputStream.getCrc32Checksum()); } }
1,898
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/util/VersionInfoTest.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.core.util; import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.junit.jupiter.api.Test; public final class VersionInfoTest { @Test public void versionIsTheSameAsMavenProject() throws Exception { assertThat(VersionInfo.SDK_VERSION).isEqualTo(getSdkVersionFromPom()); } private String getSdkVersionFromPom() throws URISyntaxException, IOException { Path pomPath = Paths.get(VersionInfo.class.getResource(".").toURI()).resolve("../../../../../../../pom.xml"); String pom = new String(Files.readAllBytes(pomPath)); Matcher match = Pattern.compile("<version>(.*)</version>").matcher(pom); if (match.find()) { return match.group(1); } throw new RuntimeException("Version not found in " + pomPath); } }
1,899