index int64 0 0 | repo_id stringlengths 26 205 | file_path stringlengths 51 246 | content stringlengths 8 433k | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/internal/ContainerCredentialsRetryPolicy.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials.internal;
import java.io.IOException;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.HttpStatusFamily;
import software.amazon.awssdk.regions.util.ResourcesEndpointRetryParameters;
import software.amazon.awssdk.regions.util.ResourcesEndpointRetryPolicy;
@SdkInternalApi
public final class ContainerCredentialsRetryPolicy implements ResourcesEndpointRetryPolicy {
/** Max number of times a request is retried before failing. */
private static final int MAX_RETRIES = 5;
@Override
public boolean shouldRetry(int retriesAttempted, ResourcesEndpointRetryParameters retryParams) {
if (retriesAttempted >= MAX_RETRIES) {
return false;
}
Integer statusCode = retryParams.getStatusCode();
if (statusCode != null && HttpStatusFamily.of(statusCode) == HttpStatusFamily.SERVER_ERROR) {
return true;
}
return retryParams.getException() instanceof IOException;
}
}
| 1,500 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/internal/CredentialSourceType.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.auth.credentials.internal;
import software.amazon.awssdk.annotations.SdkInternalApi;
@SdkInternalApi
public enum CredentialSourceType {
EC2_INSTANCE_METADATA,
ECS_CONTAINER,
ENVIRONMENT;
public static CredentialSourceType parse(String value) {
if (value.equalsIgnoreCase("Ec2InstanceMetadata")) {
return EC2_INSTANCE_METADATA;
} else if (value.equalsIgnoreCase("EcsContainer")) {
return ECS_CONTAINER;
} else if (value.equalsIgnoreCase("Environment")) {
return ENVIRONMENT;
}
throw new IllegalArgumentException(String.format("%s is not a valid credential_source", value));
}
}
| 1,501 |
0 | Create_ds/aws-sdk-java-v2/core/json-utils/src/test/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/json-utils/src/test/java/software/amazon/awssdk/protocols/jsoncore/JsonNodeTest.java | package software.amazon.awssdk.protocols.jsoncore;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.utils.StringInputStream;
public class JsonNodeTest {
private static final JsonNodeParser PARSER = JsonNode.parser();
@Test
public void parseString_works() {
assertThat(PARSER.parse("{}").isObject()).isTrue();
}
@Test
public void parseInputStream_works() {
assertThat(PARSER.parse(new StringInputStream("{}")).isObject()).isTrue();
}
@Test
public void parseByteArray_works() {
assertThat(PARSER.parse("{}".getBytes(UTF_8)).isObject()).isTrue();
}
@Test
public void parseNull_givesCorrectType() {
JsonNode node = PARSER.parse("null");
assertThat(node.isNull()).isTrue();
assertThat(node.isBoolean()).isFalse();
assertThat(node.isNumber()).isFalse();
assertThat(node.isString()).isFalse();
assertThat(node.isArray()).isFalse();
assertThat(node.isObject()).isFalse();
assertThat(node.isEmbeddedObject()).isFalse();
assertThatThrownBy(node::asBoolean).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asNumber).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asString).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asArray).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asObject).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asEmbeddedObject).isInstanceOf(UnsupportedOperationException.class);
}
@Test
public void parseBoolean_givesCorrectType() {
String[] options = { "true", "false" };
for (String option : options) {
JsonNode node = PARSER.parse(option);
assertThat(node.isNull()).isFalse();
assertThat(node.isBoolean()).isTrue();
assertThat(node.isNumber()).isFalse();
assertThat(node.isString()).isFalse();
assertThat(node.isArray()).isFalse();
assertThat(node.isObject()).isFalse();
assertThat(node.isEmbeddedObject()).isFalse();
assertThatThrownBy(node::asNumber).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asString).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asArray).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asObject).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asEmbeddedObject).isInstanceOf(UnsupportedOperationException.class);
}
}
@Test
public void parseNumber_givesCorrectType() {
String[] options = { "-1e100", "-1", "0", "1", "1e100" };
for (String option : options) {
JsonNode node = PARSER.parse(option);
assertThat(node.isNull()).isFalse();
assertThat(node.isBoolean()).isFalse();
assertThat(node.isNumber()).isTrue();
assertThat(node.isString()).isFalse();
assertThat(node.isArray()).isFalse();
assertThat(node.isObject()).isFalse();
assertThat(node.isEmbeddedObject()).isFalse();
assertThatThrownBy(node::asBoolean).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asString).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asArray).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asObject).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asEmbeddedObject).isInstanceOf(UnsupportedOperationException.class);
}
}
@Test
public void parseString_givesCorrectType() {
String[] options = { "\"\"", "\"foo\"" };
for (String option : options) {
JsonNode node = PARSER.parse(option);
assertThat(node.isNull()).isFalse();
assertThat(node.isBoolean()).isFalse();
assertThat(node.isNumber()).isFalse();
assertThat(node.isString()).isTrue();
assertThat(node.isArray()).isFalse();
assertThat(node.isObject()).isFalse();
assertThat(node.isEmbeddedObject()).isFalse();
assertThatThrownBy(node::asBoolean).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asNumber).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asArray).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asObject).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asEmbeddedObject).isInstanceOf(UnsupportedOperationException.class);
}
}
@Test
public void parseArray_givesCorrectType() {
String[] options = { "[]", "[null]" };
for (String option : options) {
JsonNode node = PARSER.parse(option);
assertThat(node.isNull()).isFalse();
assertThat(node.isBoolean()).isFalse();
assertThat(node.isNumber()).isFalse();
assertThat(node.isString()).isFalse();
assertThat(node.isArray()).isTrue();
assertThat(node.isObject()).isFalse();
assertThat(node.isEmbeddedObject()).isFalse();
assertThatThrownBy(node::asBoolean).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asNumber).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asString).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asObject).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asEmbeddedObject).isInstanceOf(UnsupportedOperationException.class);
}
}
@Test
public void parseObject_givesCorrectType() {
String[] options = { "{}", "{ \"foo\": null }" };
for (String option : options) {
JsonNode node = PARSER.parse(option);
assertThat(node.isNull()).isFalse();
assertThat(node.isBoolean()).isFalse();
assertThat(node.isNumber()).isFalse();
assertThat(node.isString()).isFalse();
assertThat(node.isArray()).isFalse();
assertThat(node.isObject()).isTrue();
assertThat(node.isEmbeddedObject()).isFalse();
assertThatThrownBy(node::asBoolean).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asNumber).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asString).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asArray).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asEmbeddedObject).isInstanceOf(UnsupportedOperationException.class);
}
}
@Test
public void parseBoolean_givesCorrectValue() {
assertThat(PARSER.parse("true").asBoolean()).isTrue();
assertThat(PARSER.parse("false").asBoolean()).isFalse();
}
@Test
public void parseNumber_givesCorrectValue() {
assertThat(PARSER.parse("0").asNumber()).isEqualTo("0");
assertThat(PARSER.parse("-1").asNumber()).isEqualTo("-1");
assertThat(PARSER.parse("1").asNumber()).isEqualTo("1");
assertThat(PARSER.parse("1e10000").asNumber()).isEqualTo("1e10000");
assertThat(PARSER.parse("-1e10000").asNumber()).isEqualTo("-1e10000");
assertThat(PARSER.parse("1.23").asNumber()).isEqualTo("1.23");
assertThat(PARSER.parse("-1.23").asNumber()).isEqualTo("-1.23");
}
@Test
public void parseString_givesCorrectValue() {
assertThat(PARSER.parse("\"foo\"").asString()).isEqualTo("foo");
assertThat(PARSER.parse("\"\"").asString()).isEqualTo("");
assertThat(PARSER.parse("\" \"").asString()).isEqualTo(" ");
assertThat(PARSER.parse("\"%20\"").asString()).isEqualTo("%20");
assertThat(PARSER.parse("\"\\\"\"").asString()).isEqualTo("\"");
assertThat(PARSER.parse("\" \"").asString()).isEqualTo(" ");
}
@Test
public void parseArray_givesCorrectValue() {
assertThat(PARSER.parse("[]").asArray()).isEmpty();
assertThat(PARSER.parse("[null, 1]").asArray()).satisfies(list -> {
assertThat(list).hasSize(2);
assertThat(list.get(0).isNull()).isTrue();
assertThat(list.get(1).asNumber()).isEqualTo("1");
});
}
@Test
public void parseObject_givesCorrectValue() {
assertThat(PARSER.parse("{}").asObject()).isEmpty();
assertThat(PARSER.parse("{\"foo\": \"bar\", \"baz\": 0}").asObject()).satisfies(map -> {
assertThat(map).hasSize(2);
assertThat(map.get("foo").asString()).isEqualTo("bar");
assertThat(map.get("baz").asNumber()).isEqualTo("0");
});
}
@Test
public void text_returnsContent() {
assertThat(PARSER.parse("null").text()).isEqualTo(null);
assertThat(PARSER.parse("0").text()).isEqualTo("0");
assertThat(PARSER.parse("\"foo\"").text()).isEqualTo("foo");
assertThat(PARSER.parse("true").text()).isEqualTo("true");
assertThat(PARSER.parse("[]").text()).isEqualTo(null);
assertThat(PARSER.parse("{}").text()).isEqualTo(null);
}
@Test
public void getString_returnsContent() {
assertThat(PARSER.parse("null").field("")).isEmpty();
assertThat(PARSER.parse("0").field("")).isEmpty();
assertThat(PARSER.parse("\"foo\"").field("")).isEmpty();
assertThat(PARSER.parse("true").field("")).isEmpty();
assertThat(PARSER.parse("[]").field("")).isEmpty();
assertThat(PARSER.parse("{\"\":0}").field("")).map(JsonNode::asNumber).hasValue("0");
}
@Test
public void getArray_returnsContent() {
assertThat(PARSER.parse("null").index(0)).isEmpty();
assertThat(PARSER.parse("0").index(0)).isEmpty();
assertThat(PARSER.parse("\"foo\"").index(0)).isEmpty();
assertThat(PARSER.parse("true").index(0)).isEmpty();
assertThat(PARSER.parse("[]").index(0)).isEmpty();
assertThat(PARSER.parse("[null]").index(0)).map(JsonNode::isNull).hasValue(true);
assertThat(PARSER.parse("{}").field("")).isEmpty();
}
@Test
public void toStringIsCorrect() {
String input = "{"
+ "\"1\": \"2\","
+ "\"3\": 4,"
+ "\"5\": null,"
+ "\"6\": false,"
+ "\"7\": [[{}]],"
+ "\"8\": \"\\\\n\\\"\""
+ "}";
assertThat(PARSER.parse(input).toString()).isEqualTo(input);
}
@Test
public void exceptionsIncludeErrorLocation() {
assertThatThrownBy(() -> PARSER.parse("{{foo}")).hasMessageContaining("foo");
}
@Test
public void removeErrorLocations_removesErrorLocations() {
assertThatThrownBy(() -> JsonNode.parserBuilder()
.removeErrorLocations(true)
.build()
.parse("{{foo}"))
.satisfies(exception -> {
Throwable cause = exception;
while (cause != null) {
assertThat(cause.getMessage()).doesNotContain("foo");
cause = cause.getCause();
}
});
}
} | 1,502 |
0 | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols/jsoncore/JsonNode.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.jsoncore;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.protocols.jsoncore.internal.ObjectJsonNode;
import software.amazon.awssdk.thirdparty.jackson.core.JsonFactory;
/**
* A node in a JSON document. Either a number, string, boolean, array, object or null. Also can be an embedded object,
* which is a non-standard type used in JSON extensions, like CBOR.
*
* <p>Created from a JSON document via {@link #parser()} or {@link #parserBuilder()}.
*
* <p>The type of node can be determined using "is" methods like {@link #isNumber()} and {@link #isString()}.
* Once the type is determined, the value of the node can be extracted via the "as" methods, like {@link #asNumber()}
* and {@link #asString()}.
*/
@SdkProtectedApi
public interface JsonNode {
/**
* Create a {@link JsonNodeParser} for generating a {@link JsonNode} from a JSON document.
*/
static JsonNodeParser parser() {
return JsonNodeParser.create();
}
/**
* Create a {@link JsonNodeParser.Builder} for generating a {@link JsonNode} from a JSON document.
*/
static JsonNodeParser.Builder parserBuilder() {
return JsonNodeParser.builder();
}
/**
* Return an empty object node.
*/
static JsonNode emptyObjectNode() {
return new ObjectJsonNode(Collections.emptyMap());
}
/**
* Returns true if this node represents a JSON number: https://datatracker.ietf.org/doc/html/rfc8259#section-6
*
* @see #asNumber()
*/
default boolean isNumber() {
return false;
}
/**
* Returns true if this node represents a JSON string: https://datatracker.ietf.org/doc/html/rfc8259#section-7
*
* @see #asString()
*/
default boolean isString() {
return false;
}
/**
* Returns true if this node represents a JSON boolean: https://datatracker.ietf.org/doc/html/rfc8259#section-3
*
* @see #asBoolean()
*/
default boolean isBoolean() {
return false;
}
/**
* Returns true if this node represents a JSON null: https://datatracker.ietf.org/doc/html/rfc8259#section-3
*/
default boolean isNull() {
return false;
}
/**
* Returns true if this node represents a JSON array: https://datatracker.ietf.org/doc/html/rfc8259#section-5
*
* @see #asArray()
*/
default boolean isArray() {
return false;
}
/**
* Returns true if this node represents a JSON object: https://datatracker.ietf.org/doc/html/rfc8259#section-4
*
* @see #asObject()
*/
default boolean isObject() {
return false;
}
/**
* Returns true if this node represents a JSON "embedded object". This non-standard type is associated with JSON extensions,
* like CBOR or ION. It allows additional data types to be embedded in a JSON document, like a timestamp or a raw byte array.
*
* <p>Users who are only concerned with handling JSON can ignore this field. It will only be present when using a custom
* {@link JsonFactory} via {@link JsonNodeParser.Builder#jsonFactory(JsonFactory)}.
*
* @see #asEmbeddedObject()
*/
default boolean isEmbeddedObject() {
return false;
}
/**
* When {@link #isNumber()} is true, this returns the number associated with this node. This will throw an exception if
* {@link #isNumber()} is false.
*
* @see #text()
*/
String asNumber();
/**
* When {@link #isString()}, is true, this returns the string associated with this node. This will throw an exception if
* {@link #isString()} ()} is false.
*/
String asString();
/**
* When {@link #isBoolean()} is true, this returns the boolean associated with this node. This will throw an exception if
* {@link #isBoolean()} is false.
*/
boolean asBoolean();
/**
* When {@link #isArray()} is true, this returns the array associated with this node. This will throw an exception if
* {@link #isArray()} is false.
*/
List<JsonNode> asArray();
/**
* When {@link #isObject()} is true, this returns the object associated with this node. This will throw an exception if
* {@link #isObject()} is false.
*/
Map<String, JsonNode> asObject();
/**
* When {@link #isEmbeddedObject()} is true, this returns the embedded object associated with this node. This will throw
* an exception if {@link #isEmbeddedObject()} is false.
*
* @see #isEmbeddedObject()
*/
Object asEmbeddedObject();
/**
* Visit this node using the provided visitor.
*/
<T> T visit(JsonNodeVisitor<T> visitor);
/**
* When {@link #isString()}, {@link #isBoolean()}, or {@link #isNumber()} is true, this will return the value of this node
* as a textual string. If this is any other type, this will return null.
*/
String text();
/**
* When {@link #isObject()} is true, this will return the result of {@code Optional.ofNullable(asObject().get(child))}. If
* this is any other type, this will return {@link Optional#empty()}.
*/
default Optional<JsonNode> field(String child) {
return Optional.empty();
}
/**
* When {@link #isArray()} is true, this will return the result of {@code asArray().get(child)} if child is within bounds. If
* this is any other type or the child is out of bounds, this will return {@link Optional#empty()}.
*/
default Optional<JsonNode> index(int child) {
return Optional.empty();
}
}
| 1,503 |
0 | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols/jsoncore/JsonNodeVisitor.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.jsoncore;
import java.util.List;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Converter from a {@link JsonNode} to a new type. This is usually invoked via {@link JsonNode#visit(JsonNodeVisitor)}.
*/
@SdkProtectedApi
public interface JsonNodeVisitor<T> {
/**
* Invoked if {@link JsonNode#visit(JsonNodeVisitor)} is invoked on a null JSON node.
*/
T visitNull();
/**
* Invoked if {@link JsonNode#visit(JsonNodeVisitor)} is invoked on a boolean JSON node.
*/
T visitBoolean(boolean bool);
/**
* Invoked if {@link JsonNode#visit(JsonNodeVisitor)} is invoked on a number JSON node.
*/
T visitNumber(String number);
/**
* Invoked if {@link JsonNode#visit(JsonNodeVisitor)} is invoked on a string JSON node.
*/
T visitString(String string);
/**
* Invoked if {@link JsonNode#visit(JsonNodeVisitor)} is invoked on an array JSON node.
*/
T visitArray(List<JsonNode> array);
/**
* Invoked if {@link JsonNode#visit(JsonNodeVisitor)} is invoked on an object JSON node.
*/
T visitObject(Map<String, JsonNode> object);
/**
* Invoked if {@link JsonNode#visit(JsonNodeVisitor)} is invoked on an embedded object JSON node.
*/
T visitEmbeddedObject(Object embeddedObject);
}
| 1,504 |
0 | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols/jsoncore/JsonNodeParser.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.jsoncore;
import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.protocols.jsoncore.internal.ArrayJsonNode;
import software.amazon.awssdk.protocols.jsoncore.internal.BooleanJsonNode;
import software.amazon.awssdk.protocols.jsoncore.internal.EmbeddedObjectJsonNode;
import software.amazon.awssdk.protocols.jsoncore.internal.NullJsonNode;
import software.amazon.awssdk.protocols.jsoncore.internal.NumberJsonNode;
import software.amazon.awssdk.protocols.jsoncore.internal.ObjectJsonNode;
import software.amazon.awssdk.protocols.jsoncore.internal.StringJsonNode;
import software.amazon.awssdk.thirdparty.jackson.core.JsonFactory;
import software.amazon.awssdk.thirdparty.jackson.core.JsonParseException;
import software.amazon.awssdk.thirdparty.jackson.core.JsonParser;
import software.amazon.awssdk.thirdparty.jackson.core.JsonToken;
import software.amazon.awssdk.thirdparty.jackson.core.json.JsonReadFeature;
/**
* Parses an JSON document into a simple DOM-like structure, {@link JsonNode}.
*
* <p>This is created using {@link #create()} or {@link #builder()}.
*/
@SdkProtectedApi
public final class JsonNodeParser {
/**
* The default {@link JsonFactory} used for {@link #create()} or if a factory is not configured via
* {@link Builder#jsonFactory(JsonFactory)}.
*/
public static final JsonFactory DEFAULT_JSON_FACTORY =
JsonFactory.builder()
.configure(JsonReadFeature.ALLOW_JAVA_COMMENTS, true)
.build();
private final boolean removeErrorLocations;
private final JsonFactory jsonFactory;
private JsonNodeParser(Builder builder) {
this.removeErrorLocations = builder.removeErrorLocations;
this.jsonFactory = builder.jsonFactory;
}
/**
* Create a parser using the default configuration.
*/
public static JsonNodeParser create() {
return builder().build();
}
/**
* Create a parser using custom configuration.
*/
public static JsonNodeParser.Builder builder() {
return new Builder();
}
/**
* Parse the provided {@link InputStream} into a {@link JsonNode}.
*/
public JsonNode parse(InputStream content) {
return invokeSafely(() -> {
try (JsonParser parser = jsonFactory.createParser(content)
.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false)) {
return parse(parser);
}
});
}
/**
* Parse the provided {@code byte[]} into a {@link JsonNode}.
*/
public JsonNode parse(byte[] content) {
return invokeSafely(() -> {
try (JsonParser parser = jsonFactory.createParser(content)
.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false)) {
return parse(parser);
}
});
}
/**
* Parse the provided {@link String} into a {@link JsonNode}.
*/
public JsonNode parse(String content) {
return invokeSafely(() -> {
try (JsonParser parser = jsonFactory.createParser(content)
.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false)) {
return parse(parser);
}
});
}
private JsonNode parse(JsonParser parser) throws IOException {
try {
return parseToken(parser, parser.nextToken());
} catch (Exception e) {
removeErrorLocationsIfRequired(e);
throw e;
}
}
private void removeErrorLocationsIfRequired(Throwable exception) {
if (removeErrorLocations) {
removeErrorLocations(exception);
}
}
private void removeErrorLocations(Throwable exception) {
if (exception == null) {
return;
}
if (exception instanceof JsonParseException) {
((JsonParseException) exception).clearLocation();
}
removeErrorLocations(exception.getCause());
}
private JsonNode parseToken(JsonParser parser, JsonToken token) throws IOException {
if (token == null) {
return null;
}
switch (token) {
case VALUE_STRING:
return new StringJsonNode(parser.getText());
case VALUE_FALSE:
return new BooleanJsonNode(false);
case VALUE_TRUE:
return new BooleanJsonNode(true);
case VALUE_NULL:
return NullJsonNode.instance();
case VALUE_NUMBER_FLOAT:
case VALUE_NUMBER_INT:
return new NumberJsonNode(parser.getText());
case START_OBJECT:
return parseObject(parser);
case START_ARRAY:
return parseArray(parser);
case VALUE_EMBEDDED_OBJECT:
return new EmbeddedObjectJsonNode(parser.getEmbeddedObject());
default:
throw new IllegalArgumentException("Unexpected JSON token - " + token);
}
}
private JsonNode parseObject(JsonParser parser) throws IOException {
JsonToken currentToken = parser.nextToken();
Map<String, JsonNode> object = new LinkedHashMap<>();
while (currentToken != JsonToken.END_OBJECT) {
String fieldName = parser.getText();
object.put(fieldName, parseToken(parser, parser.nextToken()));
currentToken = parser.nextToken();
}
return new ObjectJsonNode(object);
}
private JsonNode parseArray(JsonParser parser) throws IOException {
JsonToken currentToken = parser.nextToken();
List<JsonNode> array = new ArrayList<>();
while (currentToken != JsonToken.END_ARRAY) {
array.add(parseToken(parser, currentToken));
currentToken = parser.nextToken();
}
return new ArrayJsonNode(array);
}
/**
* A builder for configuring and creating {@link JsonNodeParser}. Created via {@link #builder()}.
*/
public static final class Builder {
private JsonFactory jsonFactory = DEFAULT_JSON_FACTORY;
private boolean removeErrorLocations = false;
private Builder() {
}
/**
* Whether error locations should be removed if parsing fails. This prevents the content of the JSON from appearing in
* error messages. This is useful when the content of the JSON may be sensitive and not want to be logged.
*
* <p>By default, this is false.
*/
public Builder removeErrorLocations(boolean removeErrorLocations) {
this.removeErrorLocations = removeErrorLocations;
return this;
}
/**
* The {@link JsonFactory} implementation to be used when parsing the input. This allows JSON extensions like CBOR or
* Ion to be supported.
*
* <p>It's highly recommended us use a shared {@code JsonFactory} where possible, so they should be stored statically:
* http://wiki.fasterxml.com/JacksonBestPracticesPerformance
*
* <p>By default, this is {@link #DEFAULT_JSON_FACTORY}.
*/
public Builder jsonFactory(JsonFactory jsonFactory) {
this.jsonFactory = jsonFactory;
return this;
}
/**
* Build a {@link JsonNodeParser} based on the current configuration of this builder.
*/
public JsonNodeParser build() {
return new JsonNodeParser(this);
}
}
}
| 1,505 |
0 | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols/jsoncore/JsonWriter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.jsoncore;
import static software.amazon.awssdk.protocols.jsoncore.JsonNodeParser.DEFAULT_JSON_FACTORY;
import static software.amazon.awssdk.utils.DateUtils.formatUnixTimestampInstant;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.time.Instant;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.thirdparty.jackson.core.JsonFactory;
import software.amazon.awssdk.thirdparty.jackson.core.JsonGenerator;
import software.amazon.awssdk.utils.BinaryUtils;
import software.amazon.awssdk.utils.FunctionalUtils;
import software.amazon.awssdk.utils.SdkAutoCloseable;
/**
* Thin wrapper around Jackson's JSON generator.
*/
@SdkProtectedApi
public class JsonWriter implements SdkAutoCloseable {
private static final int DEFAULT_BUFFER_SIZE = 1024;
private final ByteArrayOutputStream baos;
private final JsonGenerator generator;
private JsonWriter(Builder builder) {
JsonGeneratorFactory jsonGeneratorFactory = builder.jsonGeneratorFactory != null
? builder.jsonGeneratorFactory
: DEFAULT_JSON_FACTORY::createGenerator;
try {
baos = new ByteArrayOutputStream(DEFAULT_BUFFER_SIZE);
generator = jsonGeneratorFactory.createGenerator(baos);
} catch (IOException e) {
throw new JsonGenerationException(e);
}
}
public static JsonWriter create() {
return builder().build();
}
public static JsonWriter.Builder builder() {
return new Builder();
}
public JsonWriter writeStartArray() {
return unsafeWrite(generator::writeStartArray);
}
public JsonWriter writeEndArray() {
return unsafeWrite(generator::writeEndArray);
}
public JsonWriter writeNull() {
return unsafeWrite(generator::writeEndArray);
}
public JsonWriter writeStartObject() {
return unsafeWrite(generator::writeStartObject);
}
public JsonWriter writeEndObject() {
return unsafeWrite(generator::writeEndObject);
}
public JsonWriter writeFieldName(String fieldName) {
return unsafeWrite(() -> generator.writeFieldName(fieldName));
}
public JsonWriter writeValue(String val) {
return unsafeWrite(() -> generator.writeString(val));
}
public JsonWriter writeValue(boolean bool) {
return unsafeWrite(() -> generator.writeBoolean(bool));
}
public JsonWriter writeValue(long val) {
return unsafeWrite(() -> generator.writeNumber(val));
}
public JsonWriter writeValue(double val) {
return unsafeWrite(() -> generator.writeNumber(val));
}
public JsonWriter writeValue(float val) {
return unsafeWrite(() -> generator.writeNumber(val));
}
public JsonWriter writeValue(short val) {
return unsafeWrite(() -> generator.writeNumber(val));
}
public JsonWriter writeValue(int val) {
return unsafeWrite(() -> generator.writeNumber(val));
}
public JsonWriter writeValue(ByteBuffer bytes) {
return unsafeWrite(() -> generator.writeBinary(BinaryUtils.copyBytesFrom(bytes)));
}
public JsonWriter writeValue(Instant instant) {
return unsafeWrite(() -> generator.writeNumber(formatUnixTimestampInstant(instant)));
}
public JsonWriter writeValue(BigDecimal value) {
return unsafeWrite(() -> generator.writeString(value.toString()));
}
public JsonWriter writeValue(BigInteger value) {
return unsafeWrite(() -> generator.writeNumber(value));
}
public JsonWriter writeNumber(String number) {
return unsafeWrite(() -> generator.writeNumber(number));
}
/**
* Closes the generator and flushes to write. Must be called when finished writing JSON
* content.
*/
@Override
public void close() {
try {
generator.close();
} catch (IOException e) {
throw new JsonGenerationException(e);
}
}
/**
* Get the JSON content as a UTF-8 encoded byte array. It is recommended to hold onto the array
* reference rather then making repeated calls to this method as a new array will be created
* each time.
*
* @return Array of UTF-8 encoded bytes that make up the generated JSON.
*/
public byte[] getBytes() {
close();
return baos.toByteArray();
}
private JsonWriter unsafeWrite(FunctionalUtils.UnsafeRunnable r) {
try {
r.run();
} catch (Exception e) {
throw new JsonGenerationException(e);
}
return this;
}
/**
* A builder for configuring and creating {@link JsonWriter}. Created via {@link #builder()}.
*/
public static final class Builder {
private JsonGeneratorFactory jsonGeneratorFactory;
private Builder() {
}
/**
* The {@link JsonFactory} implementation to be used when parsing the input. This allows JSON extensions like CBOR or
* Ion to be supported.
*
* <p>It's highly recommended to use a shared {@code JsonFactory} where possible, so they should be stored statically:
* http://wiki.fasterxml.com/JacksonBestPracticesPerformance
*
* <p>By default, this is {@link JsonNodeParser#DEFAULT_JSON_FACTORY}.
*
* <p>Setting this value will also override any values set via {@link #jsonGeneratorFactory}.
*/
public JsonWriter.Builder jsonFactory(JsonFactory jsonFactory) {
jsonGeneratorFactory(jsonFactory::createGenerator);
return this;
}
/**
* A factory for {@link JsonGenerator}s based on an {@link OutputStream}. This allows custom JSON generator
* configuration, like pretty-printing output.
*
* <p>It's highly recommended to use a shared {@code JsonFactory} within this generator factory, where possible, so they
* should be stored statically: http://wiki.fasterxml.com/JacksonBestPracticesPerformance
*
* <p>By default, this delegates to {@link JsonNodeParser#DEFAULT_JSON_FACTORY} to create the generator.
*
* <p>Setting this value will also override any values set via {@link #jsonFactory}.
*/
public JsonWriter.Builder jsonGeneratorFactory(JsonGeneratorFactory jsonGeneratorFactory) {
this.jsonGeneratorFactory = jsonGeneratorFactory;
return this;
}
/**
* Build a {@link JsonNodeParser} based on the current configuration of this builder.
*/
public JsonWriter build() {
return new JsonWriter(this);
}
}
/**
* Generate a {@link JsonGenerator} for a {@link OutputStream}. This will get called once for each "write" call.
*/
@FunctionalInterface
public interface JsonGeneratorFactory {
JsonGenerator createGenerator(OutputStream outputStream) throws IOException;
}
/**
* Indicates an issue writing JSON content.
*/
public static class JsonGenerationException extends RuntimeException {
public JsonGenerationException(Throwable t) {
super(t);
}
}
}
| 1,506 |
0 | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols/jsoncore | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols/jsoncore/internal/BooleanJsonNode.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.jsoncore.internal;
import java.util.List;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.protocols.jsoncore.JsonNodeVisitor;
/**
* A boolean {@link JsonNode}.
*/
@SdkInternalApi
public final class BooleanJsonNode implements JsonNode {
private final boolean value;
public BooleanJsonNode(boolean value) {
this.value = value;
}
@Override
public boolean isBoolean() {
return true;
}
@Override
public String asNumber() {
throw new UnsupportedOperationException("A JSON boolean cannot be converted to a number.");
}
@Override
public String asString() {
throw new UnsupportedOperationException("A JSON boolean cannot be converted to a string.");
}
@Override
public boolean asBoolean() {
return value;
}
@Override
public List<JsonNode> asArray() {
throw new UnsupportedOperationException("A JSON boolean cannot be converted to an array.");
}
@Override
public Map<String, JsonNode> asObject() {
throw new UnsupportedOperationException("A JSON boolean cannot be converted to an object.");
}
@Override
public Object asEmbeddedObject() {
throw new UnsupportedOperationException("A JSON boolean cannot be converted to an embedded object.");
}
@Override
public <T> T visit(JsonNodeVisitor<T> visitor) {
return visitor.visitBoolean(asBoolean());
}
@Override
public String text() {
return Boolean.toString(value);
}
@Override
public String toString() {
return Boolean.toString(value);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
BooleanJsonNode that = (BooleanJsonNode) o;
return value == that.value;
}
@Override
public int hashCode() {
return (value ? 1 : 0);
}
}
| 1,507 |
0 | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols/jsoncore | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols/jsoncore/internal/NullJsonNode.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.jsoncore.internal;
import java.util.List;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.protocols.jsoncore.JsonNodeVisitor;
/**
* A null {@link JsonNode}.
*/
@SdkInternalApi
public final class NullJsonNode implements JsonNode {
private static final NullJsonNode INSTANCE = new NullJsonNode();
private NullJsonNode() {
}
public static NullJsonNode instance() {
return INSTANCE;
}
@Override
public boolean isNull() {
return true;
}
@Override
public String asNumber() {
throw new UnsupportedOperationException("A JSON null cannot be converted to a number.");
}
@Override
public String asString() {
throw new UnsupportedOperationException("A JSON null cannot be converted to a string.");
}
@Override
public boolean asBoolean() {
throw new UnsupportedOperationException("A JSON null cannot be converted to a boolean.");
}
@Override
public List<JsonNode> asArray() {
throw new UnsupportedOperationException("A JSON null cannot be converted to an array.");
}
@Override
public Map<String, JsonNode> asObject() {
throw new UnsupportedOperationException("A JSON null cannot be converted to an object.");
}
@Override
public Object asEmbeddedObject() {
throw new UnsupportedOperationException("A JSON null cannot be converted to an embedded object.");
}
@Override
public <T> T visit(JsonNodeVisitor<T> visitor) {
return visitor.visitNull();
}
@Override
public String text() {
return null;
}
@Override
public String toString() {
return "null";
}
@Override
public boolean equals(Object obj) {
return this == obj;
}
@Override
public int hashCode() {
return 0;
}
}
| 1,508 |
0 | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols/jsoncore | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols/jsoncore/internal/ObjectJsonNode.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.jsoncore.internal;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.protocols.jsoncore.JsonNodeVisitor;
/**
* An object {@link JsonNode}.
*/
@SdkInternalApi
public final class ObjectJsonNode implements JsonNode {
private final Map<String, JsonNode> value;
public ObjectJsonNode(Map<String, JsonNode> value) {
this.value = value;
}
@Override
public boolean isObject() {
return true;
}
@Override
public String asNumber() {
throw new UnsupportedOperationException("A JSON object cannot be converted to a number.");
}
@Override
public String asString() {
throw new UnsupportedOperationException("A JSON object cannot be converted to a string.");
}
@Override
public boolean asBoolean() {
throw new UnsupportedOperationException("A JSON object cannot be converted to a boolean.");
}
@Override
public List<JsonNode> asArray() {
throw new UnsupportedOperationException("A JSON object cannot be converted to an array.");
}
@Override
public Map<String, JsonNode> asObject() {
return value;
}
@Override
public <T> T visit(JsonNodeVisitor<T> visitor) {
return visitor.visitObject(asObject());
}
@Override
public Object asEmbeddedObject() {
throw new UnsupportedOperationException("A JSON object cannot be converted to an embedded object.");
}
@Override
public String text() {
return null;
}
@Override
public Optional<JsonNode> field(String child) {
return Optional.ofNullable(value.get(child));
}
@Override
public String toString() {
if (value.isEmpty()) {
return "{}";
}
StringBuilder output = new StringBuilder();
output.append("{");
value.forEach((k, v) -> output.append("\"").append(k).append("\": ")
.append(v.toString()).append(","));
output.setCharAt(output.length() - 1, '}');
return output.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ObjectJsonNode that = (ObjectJsonNode) o;
return value.equals(that.value);
}
@Override
public int hashCode() {
return value.hashCode();
}
}
| 1,509 |
0 | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols/jsoncore | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols/jsoncore/internal/NumberJsonNode.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.jsoncore.internal;
import java.util.List;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.protocols.jsoncore.JsonNodeVisitor;
/**
* A numeric {@link JsonNode}.
*/
@SdkInternalApi
public final class NumberJsonNode implements JsonNode {
private final String value;
public NumberJsonNode(String value) {
this.value = value;
}
@Override
public boolean isNumber() {
return true;
}
@Override
public String asNumber() {
return value;
}
@Override
public String asString() {
throw new UnsupportedOperationException("A JSON number cannot be converted to a string.");
}
@Override
public boolean asBoolean() {
throw new UnsupportedOperationException("A JSON number cannot be converted to a boolean.");
}
@Override
public List<JsonNode> asArray() {
throw new UnsupportedOperationException("A JSON number cannot be converted to an array.");
}
@Override
public Map<String, JsonNode> asObject() {
throw new UnsupportedOperationException("A JSON number cannot be converted to an object.");
}
@Override
public Object asEmbeddedObject() {
throw new UnsupportedOperationException("A JSON number cannot be converted to an embedded object.");
}
@Override
public <T> T visit(JsonNodeVisitor<T> visitor) {
return visitor.visitNumber(asNumber());
}
@Override
public String text() {
return value;
}
@Override
public String toString() {
return value;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
NumberJsonNode that = (NumberJsonNode) o;
return value.equals(that.value);
}
@Override
public int hashCode() {
return value.hashCode();
}
}
| 1,510 |
0 | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols/jsoncore | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols/jsoncore/internal/EmbeddedObjectJsonNode.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.jsoncore.internal;
import java.util.List;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.protocols.jsoncore.JsonNodeVisitor;
/**
* An embedded object {@link JsonNode}.
*/
@SdkInternalApi
public final class EmbeddedObjectJsonNode implements JsonNode {
private final Object embeddedObject;
public EmbeddedObjectJsonNode(Object embeddedObject) {
this.embeddedObject = embeddedObject;
}
@Override
public boolean isEmbeddedObject() {
return true;
}
@Override
public String asNumber() {
throw new UnsupportedOperationException("A JSON embedded object cannot be converted to a number.");
}
@Override
public String asString() {
throw new UnsupportedOperationException("A JSON embedded object cannot be converted to a string.");
}
@Override
public boolean asBoolean() {
throw new UnsupportedOperationException("A JSON embedded object cannot be converted to a boolean.");
}
@Override
public List<JsonNode> asArray() {
throw new UnsupportedOperationException("A JSON embedded object cannot be converted to an array.");
}
@Override
public Map<String, JsonNode> asObject() {
throw new UnsupportedOperationException("A JSON embedded object cannot be converted to an object.");
}
@Override
public Object asEmbeddedObject() {
return embeddedObject;
}
@Override
public <T> T visit(JsonNodeVisitor<T> visitor) {
return visitor.visitEmbeddedObject(asEmbeddedObject());
}
@Override
public String text() {
return null;
}
@Override
public String toString() {
return "<<Embedded Object (" + embeddedObject.getClass().getSimpleName() + ")>>";
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EmbeddedObjectJsonNode that = (EmbeddedObjectJsonNode) o;
return embeddedObject.equals(that.embeddedObject);
}
@Override
public int hashCode() {
return embeddedObject.hashCode();
}
}
| 1,511 |
0 | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols/jsoncore | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols/jsoncore/internal/StringJsonNode.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.jsoncore.internal;
import java.util.List;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.protocols.jsoncore.JsonNodeVisitor;
import software.amazon.awssdk.utils.Validate;
/**
* A string {@link JsonNode}.
*/
@SdkInternalApi
public final class StringJsonNode implements JsonNode {
private final String value;
public StringJsonNode(String value) {
Validate.paramNotNull(value, "value");
this.value = value;
}
@Override
public boolean isString() {
return true;
}
@Override
public String asNumber() {
throw new UnsupportedOperationException("A JSON string cannot be converted to a number.");
}
@Override
public String asString() {
return value;
}
@Override
public boolean asBoolean() {
throw new UnsupportedOperationException("A JSON string cannot be converted to a boolean.");
}
@Override
public List<JsonNode> asArray() {
throw new UnsupportedOperationException("A JSON string cannot be converted to an array.");
}
@Override
public Map<String, JsonNode> asObject() {
throw new UnsupportedOperationException("A JSON string cannot be converted to an object.");
}
@Override
public Object asEmbeddedObject() {
throw new UnsupportedOperationException("A JSON string cannot be converted to an embedded object.");
}
@Override
public <T> T visit(JsonNodeVisitor<T> visitor) {
return visitor.visitString(asString());
}
@Override
public String text() {
return value;
}
@Override
public String toString() {
// Does not handle unicode control characters
return "\"" +
value.replace("\\", "\\\\")
.replace("\"", "\\\"")
+ "\"";
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
StringJsonNode that = (StringJsonNode) o;
return value.equals(that.value);
}
@Override
public int hashCode() {
return value.hashCode();
}
} | 1,512 |
0 | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols/jsoncore | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols/jsoncore/internal/ArrayJsonNode.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.jsoncore.internal;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.protocols.jsoncore.JsonNodeVisitor;
/**
* An array {@link JsonNode}.
*/
@SdkInternalApi
public final class ArrayJsonNode implements JsonNode {
private final List<JsonNode> value;
public ArrayJsonNode(List<JsonNode> value) {
this.value = value;
}
@Override
public boolean isArray() {
return true;
}
@Override
public String asNumber() {
throw new UnsupportedOperationException("A JSON array cannot be converted to a number.");
}
@Override
public String asString() {
throw new UnsupportedOperationException("A JSON array cannot be converted to a string.");
}
@Override
public boolean asBoolean() {
throw new UnsupportedOperationException("A JSON array cannot be converted to a boolean.");
}
@Override
public List<JsonNode> asArray() {
return value;
}
@Override
public Map<String, JsonNode> asObject() {
throw new UnsupportedOperationException("A JSON array cannot be converted to an object.");
}
@Override
public Object asEmbeddedObject() {
throw new UnsupportedOperationException("A JSON array cannot be converted to an embedded object.");
}
@Override
public <T> T visit(JsonNodeVisitor<T> visitor) {
return visitor.visitArray(asArray());
}
@Override
public String text() {
return null;
}
@Override
public Optional<JsonNode> index(int child) {
if (child < 0 || child >= value.size()) {
return Optional.empty();
}
return Optional.of(value.get(child));
}
@Override
public String toString() {
return value.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ArrayJsonNode that = (ArrayJsonNode) o;
return value.equals(that.value);
}
@Override
public int hashCode() {
return value.hashCode();
}
}
| 1,513 |
0 | Create_ds/aws-sdk-java-v2/core/endpoints-spi/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/endpoints-spi/src/test/java/software/amazon/awssdk/endpoints/EndpointTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.endpoints;
import static org.assertj.core.api.Assertions.assertThat;
import java.net.URI;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
public class EndpointTest {
private static final EndpointAttributeKey<String> TEST_STRING_ATTR =
new EndpointAttributeKey<>("StringAttr", String.class);
@Test
public void testEqualsHashCode() {
EqualsVerifier.forClass(Endpoint.class)
.verify();
}
@Test
public void build_maximal() {
Endpoint endpoint = Endpoint.builder()
.url(URI.create("https://myservice.aws"))
.putHeader("foo", "bar")
.putHeader("foo", "baz")
.putAttribute(TEST_STRING_ATTR, "baz")
.build();
Map<String, List<String>> expectedHeaders = new HashMap<>();
expectedHeaders.put("foo", Arrays.asList("bar", "baz"));
assertThat(endpoint.url()).isEqualTo(URI.create("https://myservice.aws"));
assertThat(endpoint.headers()).isEqualTo(expectedHeaders);
assertThat(endpoint.attribute(TEST_STRING_ATTR)).isEqualTo("baz");
}
@Test
public void toBuilder_unmodified_equalToOriginal() {
Endpoint original = Endpoint.builder()
.url(URI.create("https://myservice.aws"))
.putHeader("foo", "bar")
.putAttribute(TEST_STRING_ATTR, "baz")
.build();
assertThat(original.toBuilder().build()).isEqualTo(original);
}
@Test
public void toBuilder_headersModified_notReflectedInOriginal() {
Endpoint original = Endpoint.builder()
.putHeader("foo", "bar")
.build();
original.toBuilder()
.putHeader("foo", "baz")
.build();
assertThat(original.headers().get("foo")).containsExactly("bar");
}
@Test
public void toBuilder_attrsModified_notReflectedInOriginal() {
Endpoint original = Endpoint.builder()
.putAttribute(TEST_STRING_ATTR, "foo")
.build();
original.toBuilder()
.putAttribute(TEST_STRING_ATTR, "bar")
.build();
assertThat(original.attribute(TEST_STRING_ATTR)).isEqualTo("foo");
}
}
| 1,514 |
0 | Create_ds/aws-sdk-java-v2/core/endpoints-spi/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/endpoints-spi/src/main/java/software/amazon/awssdk/endpoints/EndpointProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.endpoints;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* A marker interface for an endpoint provider. An endpoint provider takes as input a set of service-specific parameters, and
* computes an {@link Endpoint} based on the given parameters.
*/
@SdkPublicApi
public interface EndpointProvider {
}
| 1,515 |
0 | Create_ds/aws-sdk-java-v2/core/endpoints-spi/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/endpoints-spi/src/main/java/software/amazon/awssdk/endpoints/EndpointAttributeKey.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.endpoints;
import java.util.List;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* A key for adding and retrieving attributes from an {@link Endpoint} in a typesafe manner.
* @param <T> The type of the attribute.
*/
@SdkPublicApi
public final class EndpointAttributeKey<T> {
private final String name;
private final Class<T> clzz;
public EndpointAttributeKey(String name, Class<T> clzz) {
this.name = name;
this.clzz = clzz;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EndpointAttributeKey<?> that = (EndpointAttributeKey<?>) o;
if (name != null ? !name.equals(that.name) : that.name != null) {
return false;
}
return clzz != null ? clzz.equals(that.clzz) : that.clzz == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (clzz != null ? clzz.hashCode() : 0);
return result;
}
public static <E> EndpointAttributeKey<List<E>> forList(String name) {
return new EndpointAttributeKey(name, List.class);
}
}
| 1,516 |
0 | Create_ds/aws-sdk-java-v2/core/endpoints-spi/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/endpoints-spi/src/main/java/software/amazon/awssdk/endpoints/Endpoint.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.endpoints;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* Represents an endpoint computed by an {@link EndpointProvider}. And endpoint minimally defines the {@code URI}, but may also
* declare any additional headers that needed to be used, and user-defined attributes using an {@link EndpointAttributeKey}.
*/
@SdkPublicApi
public final class Endpoint {
private final URI url;
private final Map<String, List<String>> headers;
private final Map<EndpointAttributeKey<?>, Object> attributes;
private Endpoint(BuilderImpl b) {
this.url = b.url;
this.headers = b.headers;
this.attributes = b.attributes;
}
public URI url() {
return url;
}
public Map<String, List<String>> headers() {
return headers;
}
public Builder toBuilder() {
return new BuilderImpl(this);
}
@SuppressWarnings("unchecked")
public <T> T attribute(EndpointAttributeKey<T> key) {
return (T) attributes.get(key);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Endpoint endpoint = (Endpoint) o;
if (url != null ? !url.equals(endpoint.url) : endpoint.url != null) {
return false;
}
if (headers != null ? !headers.equals(endpoint.headers) : endpoint.headers != null) {
return false;
}
return attributes != null ? attributes.equals(endpoint.attributes) : endpoint.attributes == null;
}
@Override
public int hashCode() {
int result = url != null ? url.hashCode() : 0;
result = 31 * result + (headers != null ? headers.hashCode() : 0);
result = 31 * result + (attributes != null ? attributes.hashCode() : 0);
return result;
}
public static Builder builder() {
return new BuilderImpl();
}
public interface Builder {
Builder url(URI url);
Builder putHeader(String name, String value);
<T> Builder putAttribute(EndpointAttributeKey<T> key, T value);
Endpoint build();
}
private static class BuilderImpl implements Builder {
private URI url;
private final Map<String, List<String>> headers = new HashMap<>();
private final Map<EndpointAttributeKey<?>, Object> attributes = new HashMap<>();
private BuilderImpl() {
}
private BuilderImpl(Endpoint e) {
this.url = e.url;
if (e.headers != null) {
e.headers.forEach((n, v) -> {
this.headers.put(n, new ArrayList<>(v));
});
}
this.attributes.putAll(e.attributes);
}
@Override
public Builder url(URI url) {
this.url = url;
return this;
}
@Override
public Builder putHeader(String name, String value) {
List<String> values = this.headers.computeIfAbsent(name, (n) -> new ArrayList<>());
values.add(value);
return this;
}
@Override
public <T> Builder putAttribute(EndpointAttributeKey<T> key, T value) {
this.attributes.put(key, value);
return this;
}
@Override
public Endpoint build() {
return new Endpoint(this);
}
}
}
| 1,517 |
0 | Create_ds/aws-sdk-java-v2/core/http-auth-aws-crt/src/main/java/software/amazon/awssdk/http/auth/aws | Create_ds/aws-sdk-java-v2/core/http-auth-aws-crt/src/main/java/software/amazon/awssdk/http/auth/aws/crt/HttpAuthAwsCrt.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.aws.crt;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* This is a place-holder class for this module, http-auth-aws-crt. In the event that we decide to move CRT-v4a signer
* logic back to this dedicated module, no issues will arise. This module should be an optional dependency in consumers
* (http-auth-aws), and should bring in the required dependencies (aws-crt).
*/
@SdkProtectedApi
public final class HttpAuthAwsCrt {
}
| 1,518 |
0 | Create_ds/aws-sdk-java-v2/core/auth-crt/src/test/java/software/amazon/awssdk/authcrt | Create_ds/aws-sdk-java-v2/core/auth-crt/src/test/java/software/amazon/awssdk/authcrt/signer/AwsCrtV4aSignerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.authcrt.signer.internal.SigningConfigProvider;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.crt.auth.signing.AwsSigningConfig;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.regions.Region;
/**
* Functional tests for the Sigv4a signer. These tests call the CRT native signer code.
*/
@RunWith(MockitoJUnitRunner.class)
public class AwsCrtV4aSignerTest {
private SigningConfigProvider configProvider;
private AwsCrtV4aSigner v4aSigner;
@Before
public void setup() {
configProvider = new SigningConfigProvider();
v4aSigner = AwsCrtV4aSigner.create();
}
@Test
public void hostHeaderExcludesStandardHttpPort() {
SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase();
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
SdkHttpFullRequest request = testCase.requestBuilder.protocol("http")
.port(80)
.build();
SdkHttpFullRequest signed = v4aSigner.sign(request, executionAttributes);
assertThat(signed.firstMatchingHeader("Host")).hasValue("demo.us-east-1.amazonaws.com");
}
@Test
public void hostHeaderExcludesStandardHttpsPort() {
SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase();
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
SdkHttpFullRequest request = testCase.requestBuilder.protocol("https")
.port(443)
.build();
SdkHttpFullRequest signed = v4aSigner.sign(request, executionAttributes);
assertThat(signed.firstMatchingHeader("Host")).hasValue("demo.us-east-1.amazonaws.com");
}
@Test
public void hostHeaderIncludesNonStandardPorts() {
SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase();
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
SdkHttpFullRequest request = testCase.requestBuilder.protocol("http")
.port(443)
.build();
SdkHttpFullRequest signed = v4aSigner.sign(request, executionAttributes);
assertThat(signed.firstMatchingHeader("Host")).hasValue("demo.us-east-1.amazonaws.com:443");
}
@Test
public void testHeaderSigning() {
SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase();
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
SdkHttpFullRequest request = testCase.requestBuilder.build();
SdkHttpFullRequest signed = v4aSigner.sign(request, executionAttributes);
String authHeader = signed.firstMatchingHeader("Authorization").get();
String signatureKey = "Signature=";
String signatureValue = authHeader.substring(authHeader.indexOf(signatureKey) + signatureKey.length());
AwsSigningConfig signingConfig = configProvider.createCrtSigningConfig(executionAttributes);
String regionHeader = signed.firstMatchingHeader("X-Amz-Region-Set").get();
assertThat(regionHeader).isEqualTo(Region.AWS_GLOBAL.id());
assertTrue(SignerTestUtils.verifyEcdsaSignature(request, testCase.expectedCanonicalRequest, signingConfig, signatureValue));
}
@Test
public void testQuerySigning() {
SigningTestCase testCase = SignerTestUtils.createBasicQuerySigningTestCase();
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
SdkHttpFullRequest request = testCase.requestBuilder.build();
SdkHttpFullRequest signed = v4aSigner.presign(request, executionAttributes);
List<String> signatureValues = signed.rawQueryParameters().get("X-Amz-Signature");
String signatureValue = signatureValues.get(0);
List<String> regionHeader = signed.rawQueryParameters().get("X-Amz-Region-Set");
assertThat(regionHeader.get(0)).isEqualTo(Region.AWS_GLOBAL.id());
AwsSigningConfig signingConfig = configProvider.createCrtPresigningConfig(executionAttributes);
assertTrue(SignerTestUtils.verifyEcdsaSignature(request, testCase.expectedCanonicalRequest, signingConfig, signatureValue));
}
}
| 1,519 |
0 | Create_ds/aws-sdk-java-v2/core/auth-crt/src/test/java/software/amazon/awssdk/authcrt | Create_ds/aws-sdk-java-v2/core/auth-crt/src/test/java/software/amazon/awssdk/authcrt/signer/AwsCrtS3V4aSignerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.auth.signer.internal.chunkedencoding.AwsSignedChunkedEncodingInputStream;
import software.amazon.awssdk.authcrt.signer.internal.SigningConfigProvider;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.regions.Region;
/**
* Functional tests for the S3 specific Sigv4a signer. These tests call the CRT native signer code.
*/
@RunWith(MockitoJUnitRunner.class)
public class AwsCrtS3V4aSignerTest {
private SigningConfigProvider configProvider;
private AwsCrtS3V4aSigner s3V4aSigner;
@Before
public void setup() {
configProvider = new SigningConfigProvider();
s3V4aSigner = AwsCrtS3V4aSigner.create();
}
@Test
public void testS3Signing() {
SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase();
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
SdkHttpFullRequest request = testCase.requestBuilder.build();
SdkHttpFullRequest signedRequest = s3V4aSigner.sign(request, executionAttributes);
assertThat(signedRequest.firstMatchingHeader("Authorization")).isPresent();
}
@Test
public void testS3ChunkedSigning() {
SigningTestCase testCase = SignerTestUtils.createBasicChunkedSigningTestCase();
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
SdkHttpFullRequest.Builder requestBuilder = testCase.requestBuilder;
requestBuilder.uri(URI.create("http://demo.us-east-1.amazonaws.com"));
SdkHttpFullRequest request = requestBuilder.build();
SdkHttpFullRequest signedRequest = s3V4aSigner.sign(request, executionAttributes);
assertThat(signedRequest.firstMatchingHeader("Authorization")).isPresent();
assertThat(signedRequest.contentStreamProvider()).isPresent();
assertThat(signedRequest.contentStreamProvider().get().newStream()).isInstanceOf(AwsSignedChunkedEncodingInputStream.class);
}
@Test
public void testS3Presigning() {
SigningTestCase testCase = SignerTestUtils.createBasicQuerySigningTestCase();
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
SdkHttpFullRequest request = testCase.requestBuilder.build();
SdkHttpFullRequest signed = s3V4aSigner.presign(request, executionAttributes);
List<String> regionHeader = signed.rawQueryParameters().get("X-Amz-Region-Set");
assertThat(regionHeader.get(0)).isEqualTo(Region.AWS_GLOBAL.id());
}
}
| 1,520 |
0 | Create_ds/aws-sdk-java-v2/core/auth-crt/src/test/java/software/amazon/awssdk/authcrt | Create_ds/aws-sdk-java-v2/core/auth-crt/src/test/java/software/amazon/awssdk/authcrt/signer/SignerTestUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.authcrt.signer;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static software.amazon.awssdk.authcrt.signer.internal.SigningUtils.SIGNING_CLOCK;
import java.io.ByteArrayInputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
import java.util.Arrays;
import java.util.List;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute;
import software.amazon.awssdk.authcrt.signer.internal.CrtHttpRequestConverter;
import software.amazon.awssdk.authcrt.signer.internal.SigningUtils;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.crt.auth.signing.AwsSigningConfig;
import software.amazon.awssdk.crt.auth.signing.AwsSigningUtils;
import software.amazon.awssdk.crt.http.HttpRequest;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.regions.Region;
public class SignerTestUtils {
private static final String TEST_ACCESS_KEY_ID = "AKIDEXAMPLE";
private static final String TEST_SECRET_ACCESS_KEY = "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY";
private static final String TEST_VERIFICATION_PUB_X = "b6618f6a65740a99e650b33b6b4b5bd0d43b176d721a3edfea7e7d2d56d936b1";
private static final String TEST_VERIFICATION_PUB_Y = "865ed22a7eadc9c5cb9d2cbaca1b3699139fedc5043dc6661864218330c8e518";
private static final String AUTH_SIGNED_HEADER_KEY = "SignedHeaders=";
private static final String AUTH_SIGNATURE_KEY = "Signature=";
public static boolean verifyEcdsaSignature(SdkHttpFullRequest request,
String expectedCanonicalRequest,
AwsSigningConfig signingConfig,
String signatureValue) {
CrtHttpRequestConverter requestConverter = new CrtHttpRequestConverter();
HttpRequest crtRequest = requestConverter.requestToCrt(SigningUtils.sanitizeSdkRequestForCrtSigning(request));
return AwsSigningUtils.verifySigv4aEcdsaSignature(crtRequest, expectedCanonicalRequest, signingConfig,
signatureValue.getBytes(), TEST_VERIFICATION_PUB_X, TEST_VERIFICATION_PUB_Y);
}
public static AwsBasicCredentials createCredentials() {
return AwsBasicCredentials.create(TEST_ACCESS_KEY_ID, TEST_SECRET_ACCESS_KEY);
}
public static ExecutionAttributes buildBasicExecutionAttributes(SigningTestCase testCase) {
ExecutionAttributes executionAttributes = new ExecutionAttributes();
executionAttributes.putAttribute(SIGNING_CLOCK, Clock.fixed(testCase.signingTime, ZoneId.systemDefault()));
executionAttributes.putAttribute(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME, testCase.signingName);
executionAttributes.putAttribute(AwsSignerExecutionAttribute.SIGNING_REGION, Region.AWS_GLOBAL);
executionAttributes.putAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS, testCase.credentials);
return executionAttributes;
}
public static SigningTestCase createBasicHeaderSigningTestCase() {
SigningTestCase testCase = new SigningTestCase();
String data = "{\"TableName\": \"foo\"}";
testCase.requestBuilder = createHttpPostRequest(data);
testCase.signingName = "demo";
testCase.regionSet = "aws-global";
testCase.signingTime = Instant.ofEpochSecond(1596476903);
testCase.credentials = createCredentials();
testCase.expectedCanonicalRequest = "POST\n" +
"/\n" +
"\n" +
"host:demo.us-east-1.amazonaws.com\n" +
"x-amz-archive-description:test test\n" +
"x-amz-date:20200803T174823Z\n" +
"x-amz-region-set:aws-global\n" +
"\n" +
"host;x-amz-archive-description;x-amz-date;x-amz-region-set\n" +
"a15c8292b1d12abbbbe4148605f7872fbdf645618fee5ab0e8072a7b34f155e2";
return testCase;
}
public static SigningTestCase createBasicChunkedSigningTestCase() {
SigningTestCase testCase = new SigningTestCase();
String data = "{\"TableName\": \"foo\"}";
testCase.requestBuilder = createHttpPostRequest(data);
testCase.signingName = "demo";
testCase.regionSet = "aws-global";
testCase.signingTime = Instant.ofEpochSecond(1596476903);
testCase.credentials = createCredentials();
testCase.expectedCanonicalRequest = "POST\n" +
"/\n" +
"\n" +
"host:demo.us-east-1.amazonaws.com\n" +
"x-amz-archive-description:test test\n" +
"x-amz-date:20200803T174823Z\n" +
"x-amz-decoded-content-length\n" +
"x-amz-region-set:aws-global\n" +
"\n" +
"host;x-amz-archive-description;x-amz-date;x-amz-decoded-content-length;x-amz-region-set\n" +
"";
return testCase;
}
public static SigningTestCase createBasicQuerySigningTestCase() {
SigningTestCase testCase = new SigningTestCase();
testCase.requestBuilder = SdkHttpFullRequest.builder()
.method(SdkHttpMethod.GET)
.putHeader("Host", "testing.us-east-1.amazonaws.com")
.encodedPath("/test%20path/help")
.uri(URI.create("http://testing.us-east-1.amazonaws.com"));
testCase.signingName = "testing";
testCase.regionSet = "aws-global";
testCase.signingTime = Instant.ofEpochSecond(1596476801);
testCase.credentials = createCredentials();
testCase.expectedCanonicalRequest = "GET\n" +
"/test%2520path/help\n" +
"X-Amz-Algorithm=AWS4-ECDSA-P256-SHA256&X-Amz-Credential=AKIDEXAMPLE%2F20200803%2Ftesting%2Faws4_request&X-Amz-Date=20200803T174641Z&X-Amz-Expires=604800&X-Amz-Region-Set=aws-global&X-Amz-SignedHeaders=host\n" +
"host:testing.us-east-1.amazonaws.com\n" +
"\n" +
"host\n" +
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
testCase.expectedS3PresignCanonicalRequest = "GET\n" +
"/test%2520path/help\n" +
"X-Amz-Algorithm=AWS4-ECDSA-P256-SHA256&X-Amz-Credential=AKIDEXAMPLE%2F20200803%2Ftesting%2Faws4_request&X-Amz-Date=20200803T174641Z&X-Amz-Expires=604800&X-Amz-Region-Set=aws-global&X-Amz-SignedHeaders=host\n" +
"host:testing.us-east-1.amazonaws.com\n" +
"\n" +
"host\n" +
"UNSIGNED-PAYLOAD";
return testCase;
}
public static String extractSignatureFromAuthHeader(SdkHttpFullRequest signedRequest) {
String authHeader = signedRequest.firstMatchingHeader("Authorization").get();
return authHeader.substring(authHeader.indexOf(AUTH_SIGNATURE_KEY) + AUTH_SIGNATURE_KEY.length());
}
public static List<String> extractSignedHeadersFromAuthHeader(SdkHttpFullRequest signedRequest) {
String authHeader = signedRequest.firstMatchingHeader("Authorization").get();
String headers = authHeader.substring(authHeader.indexOf(AUTH_SIGNED_HEADER_KEY) + AUTH_SIGNED_HEADER_KEY.length(),
authHeader.indexOf(AUTH_SIGNATURE_KEY) - 1);
return Arrays.asList(headers.split(";"));
}
public static SdkHttpFullRequest.Builder createHttpPostRequest(String data) {
return SdkHttpFullRequest.builder()
.contentStreamProvider(() -> new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)))
.method(SdkHttpMethod.POST)
.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"));
}
public static SdkHttpFullRequest createSignedHttpRequest(String data) {
SdkHttpFullRequest.Builder requestBuilder = createHttpPostRequest(data);
requestBuilder.putHeader("Authorization", "AWS4-ECDSA-P256-SHA256 Credential=AKIDEXAMPLE/20200803/demo/aws4_request, SignedHeaders=host;x-amz-archive-description;x-amz-date;x-amz-region-set, Signature=304502201ee492c60af1667b9c1adfbafb4dfebedca45ed7f9c17711bc73bd2c0ebdbb4b022100e1108c7749acf67bb8c2e5fcf11f751fd86f8fde9bd646a47b4897023ca348d9");
requestBuilder.putHeader("X-Amz-Date", "20200803T174823Z");
requestBuilder.putHeader("X-Amz-Region-Set", "aws-global");
return requestBuilder.build();
}
public static SdkHttpFullRequest createSignedPayloadHttpRequest(String data) {
SdkHttpFullRequest.Builder requestBuilder = createHttpPostRequest(data);
requestBuilder.putHeader("Authorization", "AWS4-ECDSA-P256-SHA256 Credential=AKIDEXAMPLE/20200803/demo/aws4_request, SignedHeaders=content-length;host;x-amz-archive-description;x-amz-content-sha256;x-amz-date;x-amz-decoded-content-length;x-amz-region-set, Signature=3046022100e3594ebc9ddfe327ca5127bbce72dd2b72965c33df36e529996edff1d7b59811022100e34cb9a2a68e82f6ac86e3359a758c546cdfb59807207dc6ebfedb44abbc4ca7");
requestBuilder.putHeader("X-Amz-Date", "20200803T174823Z");
requestBuilder.putHeader("X-Amz-Region-Set", "aws-global");
requestBuilder.putHeader("x-amz-decoded-content-length", "20");
requestBuilder.putHeader("Content-Length", "353");
return requestBuilder.build();
}
public static SdkHttpFullRequest createPresignedPayloadHttpRequest(String data) {
SdkHttpFullRequest.Builder requestBuilder = createHttpPostRequest(data);
requestBuilder.putRawQueryParameter("X-Amz-Signature", "signature");
return requestBuilder.build();
}
}
| 1,521 |
0 | Create_ds/aws-sdk-java-v2/core/auth-crt/src/test/java/software/amazon/awssdk/authcrt | Create_ds/aws-sdk-java-v2/core/auth-crt/src/test/java/software/amazon/awssdk/authcrt/signer/SigningTestCase.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 java.time.Instant;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.http.SdkHttpFullRequest;
public class SigningTestCase {
public SdkHttpFullRequest.Builder requestBuilder;
public String expectedCanonicalRequest;
public String expectedS3PresignCanonicalRequest;
public String signingName;
public String regionSet;
public Instant signingTime;
public AwsBasicCredentials credentials;
}
| 1,522 |
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/AwsCrtS3V4aSignerSigningScopeTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.util.List;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute;
import software.amazon.awssdk.authcrt.signer.AwsCrtS3V4aSigner;
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.http.SdkHttpFullRequest;
import software.amazon.awssdk.regions.RegionScope;
public class AwsCrtS3V4aSignerSigningScopeTest extends BaseSigningScopeTest {
@Test
public void signing_chunkedEncoding_regionalScope_present_overrides() {
SigningTestCase testCase = SignerTestUtils.createBasicChunkedSigningTestCase();
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 testS3Presigning() {
SigningTestCase testCase = SignerTestUtils.createBasicQuerySigningTestCase();
SdkHttpFullRequest signedRequest = presignRequestWithScope(testCase, null, RegionScope.GLOBAL);
List<String> regionHeader = signedRequest.rawQueryParameters().get("X-Amz-Region-Set");
assertThat(regionHeader.get(0)).isEqualTo(RegionScope.GLOBAL.id());
}
protected SdkHttpFullRequest signRequestWithScope(SigningTestCase testCase, RegionScope defaultRegionScope,
RegionScope regionScope) {
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
if (regionScope != null) {
executionAttributes.putAttribute(AwsSignerExecutionAttribute.SIGNING_REGION_SCOPE, regionScope);
}
SdkHttpFullRequest request = testCase.requestBuilder.build();
return AwsCrtS3V4aSigner.builder().defaultRegionScope(defaultRegionScope).build().sign(request, executionAttributes);
}
protected SdkHttpFullRequest presignRequestWithScope(SigningTestCase testCase, RegionScope defaultRegionScope,
RegionScope regionScope) {
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
if (regionScope != null) {
executionAttributes.putAttribute(AwsSignerExecutionAttribute.SIGNING_REGION_SCOPE, regionScope);
}
SdkHttpFullRequest request = testCase.requestBuilder.build();
return AwsCrtS3V4aSigner.builder().defaultRegionScope(defaultRegionScope).build().presign(request, executionAttributes);
}
}
| 1,523 |
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/AwsChunkedEncodingInputStreamTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.authcrt.signer.internal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.when;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.core.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.utils.BinaryUtils;
/**
* Runs unit tests that check that the class AwsChunkedEncodingInputStream supports params required for Sigv4a chunk
* signing.
*/
@RunWith(MockitoJUnitRunner.class)
public class AwsChunkedEncodingInputStreamTest {
private static final String REQUEST_SIGNATURE;
private static final String CHUNK_SIGNATURE_1;
private static final String CHUNK_SIGNATURE_2;
private static final String CHUNK_SIGNATURE_3;
private static final String CHECKSUM_CHUNK_SIGNATURE_3;
private static final String SIGNATURE_KEY = "chunk-signature=";
private static final String EMPTY_STRING = "";
private static final String CRLF = "\r\n";
private static final int DEFAULT_CHUNK_SIZE = 128 * 1024;
private static final int SIGV4A_SIGNATURE_LENGTH = 144;
static {
byte[] tmp = new byte[140];
Arrays.fill(tmp, (byte) 0x2A);
REQUEST_SIGNATURE = new String(tmp);
tmp = new byte[144];
Arrays.fill(tmp, (byte) 0x2B);
CHUNK_SIGNATURE_1 = new String(tmp);
tmp = new byte[144];
Arrays.fill(tmp, (byte) 0x2C);
CHUNK_SIGNATURE_2 = new String(tmp);
tmp = new byte[144];
Arrays.fill(tmp, (byte) 0x2E);
CHUNK_SIGNATURE_3 = new String(tmp);
tmp = new byte[144];
Arrays.fill(tmp, (byte) 0x2F);
CHECKSUM_CHUNK_SIGNATURE_3 = new String(tmp);
}
@Mock
AwsS3V4aChunkSigner chunkSigner;
/**
* maxSizeChunks = 0, remainingBytes = 10;
* chunklen(10) = 1 + 17 + 144 + 2 + 10 + 2 = 176
* chunklen(0) = 1 + 17 + 144 + 2 + 0 + 2 = 166
* total = 0 * chunklen(default_chunk_size) + chunklen(10) + chunklen(0) = 342
*/
@Test
public void streamContentLength_smallObject_calculatedCorrectly() {
long streamContentLength =
AwsSignedChunkedEncodingInputStream.calculateStreamContentLength(10,
AwsS3V4aChunkSigner.getSignatureLength(),
AwsChunkedEncodingConfig.create());
assertThat(streamContentLength).isEqualTo(342);
}
/**
* maxSizeChunks = 1, remainingBytes = 1;
* chunklen(131072) = 5 + 17 + 144 + 2 + 131072 + 2 = 131242
* chunklen(1) = 1 + 17 + 144 + 2 + 10 + 2 = 176
* chunklen(0) = 1 + 17 + 144 + 2 + 0 + 2 = 166
* total = 1 * chunklen(default_chunk_size) + chunklen(10) + chunklen(0) = 131584
*/
@Test
public void streamContentLength_largeObject_calculatedCorrectly() {
long streamContentLength =
AwsSignedChunkedEncodingInputStream.calculateStreamContentLength(DEFAULT_CHUNK_SIZE + 10,
AwsS3V4aChunkSigner.getSignatureLength(),
AwsChunkedEncodingConfig.create());
assertThat(streamContentLength).isEqualTo(131584);
}
@Test
public void streamContentLength_differentChunkSize_calculatedCorrectly() {
int chunkSize = 64 * 1024;
AwsChunkedEncodingConfig chunkConfig = AwsChunkedEncodingConfig.builder().chunkSize(chunkSize).build();
long streamContentLength =
AwsSignedChunkedEncodingInputStream.calculateStreamContentLength(chunkSize + 10,
AwsS3V4aChunkSigner.getSignatureLength(),
chunkConfig);
assertThat(streamContentLength).isEqualTo(66048);
}
@Test(expected = IllegalArgumentException.class)
public void streamContentLength_negative_throwsException() {
AwsSignedChunkedEncodingInputStream.calculateStreamContentLength(-1,
AwsS3V4aChunkSigner.getSignatureLength(),
AwsChunkedEncodingConfig.create());
}
@Test
public void chunkedEncodingStream_smallObject_createsCorrectChunks() throws IOException {
when(chunkSigner.signChunk(any(), any())).thenReturn(CHUNK_SIGNATURE_1)
.thenReturn(CHUNK_SIGNATURE_2);
String chunkData = "helloworld";
ByteArrayInputStream input = new ByteArrayInputStream(chunkData.getBytes());
AwsSignedChunkedEncodingInputStream stream = AwsSignedChunkedEncodingInputStream.builder()
.inputStream(input)
.headerSignature(REQUEST_SIGNATURE)
.awsChunkSigner(chunkSigner)
.awsChunkedEncodingConfig(AwsChunkedEncodingConfig.create())
.build();
int expectedChunks = 2;
consumeAndVerify(stream, expectedChunks,false);
Mockito.verify(chunkSigner, times(1)).signChunk(chunkData.getBytes(StandardCharsets.UTF_8), REQUEST_SIGNATURE);
Mockito.verify(chunkSigner, times(1)).signChunk(EMPTY_STRING.getBytes(StandardCharsets.UTF_8), CHUNK_SIGNATURE_1);
}
@Test
public void chunkedEncodingStream_largeObject_createsCorrectChunks() throws IOException {
when(chunkSigner.signChunk(any(), any())).thenReturn(CHUNK_SIGNATURE_1)
.thenReturn(CHUNK_SIGNATURE_2)
.thenReturn(CHUNK_SIGNATURE_3);
String chunk1Data = StringUtils.repeat("a", DEFAULT_CHUNK_SIZE);
String chunk2Data = "a";
ByteArrayInputStream input = new ByteArrayInputStream(chunk1Data.concat(chunk2Data).getBytes());
AwsSignedChunkedEncodingInputStream stream = AwsSignedChunkedEncodingInputStream.builder()
.inputStream(input)
.headerSignature(REQUEST_SIGNATURE)
.awsChunkSigner(chunkSigner)
.awsChunkedEncodingConfig(AwsChunkedEncodingConfig.create())
.build();
int expectedChunks = 3;
consumeAndVerify(stream, expectedChunks,false);
Mockito.verify(chunkSigner, times(1)).signChunk(chunk1Data.getBytes(StandardCharsets.UTF_8), REQUEST_SIGNATURE);
Mockito.verify(chunkSigner, times(1)).signChunk(chunk2Data.getBytes(StandardCharsets.UTF_8), CHUNK_SIGNATURE_1);
Mockito.verify(chunkSigner, times(1)).signChunk(EMPTY_STRING.getBytes(StandardCharsets.UTF_8), CHUNK_SIGNATURE_2);
}
@Test
public void chunkedEncodingStream_differentChunkSize_createsCorrectChunks() throws IOException {
when(chunkSigner.signChunk(any(), any())).thenReturn(CHUNK_SIGNATURE_1)
.thenReturn(CHUNK_SIGNATURE_2)
.thenReturn(CHUNK_SIGNATURE_3);
int chunkSize = 64 * 1024;
AwsChunkedEncodingConfig chunkConfig = AwsChunkedEncodingConfig.builder().chunkSize(chunkSize).build();
String chunk1Data = StringUtils.repeat("a", chunkSize);
String chunk2Data = "a";
ByteArrayInputStream input = new ByteArrayInputStream(chunk1Data.concat(chunk2Data).getBytes());
AwsSignedChunkedEncodingInputStream stream = AwsSignedChunkedEncodingInputStream.builder()
.inputStream(input)
.headerSignature(REQUEST_SIGNATURE)
.awsChunkSigner(chunkSigner)
.awsChunkedEncodingConfig(chunkConfig)
.build();
int expectedChunks = 3;
consumeAndVerify(stream, expectedChunks,false);
Mockito.verify(chunkSigner, times(1)).signChunk(chunk1Data.getBytes(StandardCharsets.UTF_8), REQUEST_SIGNATURE);
Mockito.verify(chunkSigner, times(1)).signChunk(chunk2Data.getBytes(StandardCharsets.UTF_8), CHUNK_SIGNATURE_1);
Mockito.verify(chunkSigner, times(1)).signChunk(EMPTY_STRING.getBytes(StandardCharsets.UTF_8), CHUNK_SIGNATURE_2);
}
@Test
public void chunkedEncodingStream_emptyString_createsCorrectChunks() throws IOException {
when(chunkSigner.signChunk(any(), any())).thenReturn(CHUNK_SIGNATURE_1);
String chunkData = EMPTY_STRING;
ByteArrayInputStream input = new ByteArrayInputStream(chunkData.getBytes());
AwsSignedChunkedEncodingInputStream stream = AwsSignedChunkedEncodingInputStream.builder()
.inputStream(input)
.headerSignature(REQUEST_SIGNATURE)
.awsChunkSigner(chunkSigner)
.awsChunkedEncodingConfig(AwsChunkedEncodingConfig.create())
.build();
int expectedChunks = 1;
consumeAndVerify(stream, expectedChunks,false);
Mockito.verify(chunkSigner, times(1)).signChunk(chunkData.getBytes(StandardCharsets.UTF_8), REQUEST_SIGNATURE);
}
@Test
public void chunkedEncodingStream_smallObject_createsCorrectChunks_and_checksum() throws IOException {
when(chunkSigner.signChunk(any(), any())).thenReturn(CHUNK_SIGNATURE_1)
.thenReturn(CHUNK_SIGNATURE_2);
when(chunkSigner.signChecksumChunk(any(), any(), any())).thenReturn(CHECKSUM_CHUNK_SIGNATURE_3);
String payloadData = "helloworld";
SdkChecksum sdkChecksum = SdkChecksum.forAlgorithm(Algorithm.CRC32);
sdkChecksum.update(payloadData.getBytes(StandardCharsets.UTF_8));
ByteArrayInputStream input = new ByteArrayInputStream(payloadData.getBytes());
AwsSignedChunkedEncodingInputStream stream =
AwsSignedChunkedEncodingInputStream.builder()
.inputStream(input)
.sdkChecksum(SdkChecksum.forAlgorithm(Algorithm.CRC32))
.checksumHeaderForTrailer("x-amz-checksum-crc32")
.headerSignature(REQUEST_SIGNATURE)
.awsChunkSigner(chunkSigner)
.awsChunkedEncodingConfig(AwsChunkedEncodingConfig.create())
.build();
int expectedChunks = 2;
consumeAndVerify(stream, expectedChunks, true);
Mockito.verify(chunkSigner, times(1)).signChunk(payloadData.getBytes(StandardCharsets.UTF_8), REQUEST_SIGNATURE);
Mockito.verify(chunkSigner, times(1)).signChunk(EMPTY_STRING.getBytes(StandardCharsets.UTF_8), CHUNK_SIGNATURE_1);
Mockito.verify(chunkSigner, times(1))
.signChecksumChunk(sdkChecksum.getChecksumBytes(),CHUNK_SIGNATURE_2, "x-amz-checksum-crc32" );
}
@Test
public void chunkedEncodingStream_largeObject_createsCorrectChunks__with_checksums() throws IOException {
when(chunkSigner.signChunk(any(), any())).thenReturn(CHUNK_SIGNATURE_1)
.thenReturn(CHUNK_SIGNATURE_2)
.thenReturn(CHUNK_SIGNATURE_3);
when(chunkSigner.signChecksumChunk(any(), any(), any())).thenReturn(CHECKSUM_CHUNK_SIGNATURE_3);
String chunk1Data = StringUtils.repeat("a", DEFAULT_CHUNK_SIZE);
String chunk2Data = "a";
SdkChecksum sdkChecksum = SdkChecksum.forAlgorithm(Algorithm.CRC32);
sdkChecksum.update(chunk1Data.getBytes(StandardCharsets.UTF_8));
sdkChecksum.update(chunk2Data.getBytes(StandardCharsets.UTF_8));
ByteArrayInputStream input = new ByteArrayInputStream(chunk1Data.concat(chunk2Data).getBytes());
AwsSignedChunkedEncodingInputStream stream =
AwsSignedChunkedEncodingInputStream.builder()
.inputStream(input)
.sdkChecksum(SdkChecksum.forAlgorithm(Algorithm.CRC32))
.checksumHeaderForTrailer("x-amz-checksum-crc32")
.headerSignature(REQUEST_SIGNATURE)
.awsChunkSigner(chunkSigner)
.awsChunkedEncodingConfig(AwsChunkedEncodingConfig.create())
.build();
int expectedChunks = 3;
consumeAndVerify(stream, expectedChunks, true);
Mockito.verify(chunkSigner, times(1)).signChunk(chunk1Data.getBytes(StandardCharsets.UTF_8), REQUEST_SIGNATURE);
Mockito.verify(chunkSigner, times(1)).signChunk(chunk2Data.getBytes(StandardCharsets.UTF_8), CHUNK_SIGNATURE_1);
Mockito.verify(chunkSigner, times(1)).signChunk(EMPTY_STRING.getBytes(StandardCharsets.UTF_8), CHUNK_SIGNATURE_2);
Mockito.verify(chunkSigner, times(1))
.signChecksumChunk(sdkChecksum.getChecksumBytes(), CHUNK_SIGNATURE_3, "x-amz-checksum-crc32");
}
@Test
public void chunkedEncodingStream_emptyString_createsCorrectChunks_checksum() throws IOException {
when(chunkSigner.signChunk(any(), any())).thenReturn(CHUNK_SIGNATURE_1);
when(chunkSigner.signChecksumChunk(any(), any(), any())).thenReturn(CHECKSUM_CHUNK_SIGNATURE_3);
String chunkData = EMPTY_STRING;
SdkChecksum sdkChecksum = SdkChecksum.forAlgorithm(Algorithm.CRC32);
byte[] bytes = chunkData.getBytes(StandardCharsets.UTF_8);
ByteArrayInputStream input = new ByteArrayInputStream(chunkData.getBytes());
AwsSignedChunkedEncodingInputStream stream =
AwsSignedChunkedEncodingInputStream.builder()
.inputStream(input)
.sdkChecksum(SdkChecksum.forAlgorithm(Algorithm.CRC32))
.checksumHeaderForTrailer("x-amz-checksum-crc32")
.headerSignature(REQUEST_SIGNATURE)
.awsChunkSigner(chunkSigner)
.awsChunkedEncodingConfig(AwsChunkedEncodingConfig.create())
.build();
int expectedChunks = 1;
consumeAndVerify(stream, expectedChunks, true);
Mockito.verify(chunkSigner, times(1)).signChunk(bytes, REQUEST_SIGNATURE);
Mockito.verify(chunkSigner, times(1))
.signChecksumChunk(sdkChecksum.getChecksumBytes(), CHUNK_SIGNATURE_1, "x-amz-checksum-crc32");
}
private void consumeAndVerify(AwsSignedChunkedEncodingInputStream stream, int numChunks, boolean isTrailerChecksum) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
IOUtils.copy(stream, output);
String result = new String(output.toByteArray(), StandardCharsets.UTF_8);
assertChunks(result, numChunks, isTrailerChecksum);
}
private void assertChunks(String result, int numExpectedChunks, boolean isTrailerChecksum) {
List<String> lines = Stream.of(result.split(CRLF)).collect(Collectors.toList());
int expectedNumberOfChunks = (2 * numExpectedChunks) - 1 + (isTrailerChecksum ? 2 : 0);
assertThat(lines).hasSize(expectedNumberOfChunks);
for (int i = 0; i < lines.size(); i = i + 2) {
String chunkMetadata = lines.get(i);
boolean isTrailerSignature = isTrailerChecksum && i == lines.size() - 1;
String signatureValue = isTrailerSignature
? chunkMetadata.substring(chunkMetadata.indexOf("x-amz-trailer-signature:")
+ "x-amz-trailer-signature:".length())
: chunkMetadata.substring(chunkMetadata.indexOf(SIGNATURE_KEY) + SIGNATURE_KEY.length());
assertThat(signatureValue.length()).isEqualTo(SIGV4A_SIGNATURE_LENGTH);
}
}
}
| 1,524 |
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/DefaultAwsCrtS3V4aSignerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static software.amazon.awssdk.auth.signer.S3SignerExecutionAttribute.ENABLE_CHUNKED_ENCODING;
import static software.amazon.awssdk.auth.signer.S3SignerExecutionAttribute.ENABLE_PAYLOAD_SIGNING;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
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.internal.util.SignerMethodResolver;
import software.amazon.awssdk.authcrt.signer.AwsCrtV4aSigner;
import software.amazon.awssdk.authcrt.signer.SignerTestUtils;
import software.amazon.awssdk.authcrt.signer.SigningTestCase;
import software.amazon.awssdk.core.checksums.Algorithm;
import software.amazon.awssdk.core.checksums.ChecksumSpecs;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute;
import software.amazon.awssdk.core.interceptor.trait.HttpChecksum;
import software.amazon.awssdk.core.internal.signer.SigningMethod;
import software.amazon.awssdk.crt.auth.signing.AwsSigningConfig;
import software.amazon.awssdk.http.SdkHttpFullRequest;
/**
* Unit tests for the {@link DefaultAwsCrtS3V4aSigner}.
*/
@RunWith(MockitoJUnitRunner.class)
public class DefaultAwsCrtS3V4aSignerTest {
private static HttpChecksum HTTP_CRC32_CHECKSUM =
HttpChecksum.builder().requestAlgorithm("crc32").isRequestStreaming(true).build();
@Mock
AwsCrt4aSigningAdapter signerAdapter;
ArgumentCaptor<AwsSigningConfig> configCaptor = ArgumentCaptor.forClass(AwsSigningConfig.class);
private SigningConfigProvider configProvider;
private DefaultAwsCrtS3V4aSigner s3V4aSigner;
@Before
public void setup() {
configProvider = new SigningConfigProvider();
s3V4aSigner = new DefaultAwsCrtS3V4aSigner(signerAdapter, configProvider);
SdkHttpFullRequest unsignedPayloadSignedRequest = SignerTestUtils.createSignedHttpRequest("data");
SdkHttpFullRequest signedPayloadSignedRequest = SignerTestUtils.createSignedPayloadHttpRequest("data");
String signedPayloadSignature = SignerTestUtils.extractSignatureFromAuthHeader(signedPayloadSignedRequest);
// when(configProvider.createS3CrtSigningConfig(any())).thenReturn(new AwsSigningConfig());
when(signerAdapter.sign(any(), any())).thenReturn(new SdkSigningResult(signedPayloadSignature.getBytes(StandardCharsets.UTF_8),
signedPayloadSignedRequest));
when(signerAdapter.signRequest(any(), any())).thenReturn(unsignedPayloadSignedRequest);
}
@Test
public void when_credentials_are_anonymous_return_request() {
SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase();
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
executionAttributes.putAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS,
AnonymousCredentialsProvider.create().resolveCredentials());
SdkHttpFullRequest request = testCase.requestBuilder.build();
SdkHttpFullRequest signedRequest = s3V4aSigner.sign(request, executionAttributes);
assertThat(signedRequest).isEqualTo(request);
}
@Test
public void no_special_configuration_does_not_sign_payload() {
SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase();
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
SdkHttpFullRequest request = testCase.requestBuilder.build();
SdkHttpFullRequest signedRequest = s3V4aSigner.sign(request, executionAttributes);
verifyUnsignedPayload(signedRequest);
}
@Test
public void protocol_http_triggers_payload_signing() {
SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase();
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
SdkHttpFullRequest.Builder requestBuilder = testCase.requestBuilder;
requestBuilder.uri(URI.create("http://demo.us-east-1.amazonaws.com"));
SdkHttpFullRequest signedRequest = s3V4aSigner.sign(requestBuilder.build(), executionAttributes);
verifySignedPayload(signedRequest);
}
@Test
public void protocol_http_triggers_payload_signing_with_trailer_checksums() {
SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase();
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
executionAttributes.putAttribute(SdkInternalExecutionAttribute.HTTP_CHECKSUM, HTTP_CRC32_CHECKSUM);
SdkHttpFullRequest.Builder requestBuilder = testCase.requestBuilder;
requestBuilder.uri(URI.create("http://demo.us-east-1.amazonaws.com"));
SdkHttpFullRequest signedRequest = s3V4aSigner.sign(requestBuilder.build(), executionAttributes);
verifySignedChecksumPayload(signedRequest);
}
@Test
public void unsigned_payload_signing_with_trailer_checksums() {
SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase();
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
executionAttributes.putAttribute(SdkInternalExecutionAttribute.HTTP_CHECKSUM, HTTP_CRC32_CHECKSUM);
SdkHttpFullRequest request = testCase.requestBuilder.build();
SdkHttpFullRequest signedRequest = s3V4aSigner.sign(request, executionAttributes);
verifyUnsignedPayloadWithTrailerChecksum(signedRequest);
}
@Test
public void payloadSigning_AND_chunkedEnabled_triggers_payload_signing() {
SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase();
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
executionAttributes.putAttribute(S3SignerExecutionAttribute.ENABLE_PAYLOAD_SIGNING, true);
executionAttributes.putAttribute(S3SignerExecutionAttribute.ENABLE_CHUNKED_ENCODING, true);
SdkHttpFullRequest signedRequest = s3V4aSigner.sign(testCase.requestBuilder.build(), executionAttributes);
verifySignedPayload(signedRequest);
}
@Test
public void payloadSigning_and_chunked_disabled_does_not_sign_payload() {
SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase();
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
executionAttributes.putAttribute(S3SignerExecutionAttribute.ENABLE_PAYLOAD_SIGNING, true);
executionAttributes.putAttribute(S3SignerExecutionAttribute.ENABLE_CHUNKED_ENCODING, false);
SdkHttpFullRequest signedRequest = s3V4aSigner.sign(testCase.requestBuilder.build(), executionAttributes);
verifyUnsignedPayload(signedRequest);
}
@Test
public void no_payloadSigning_and_chunkedEnabled_does_not_sign_payload() {
SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase();
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
executionAttributes.putAttribute(S3SignerExecutionAttribute.ENABLE_PAYLOAD_SIGNING, false);
executionAttributes.putAttribute(S3SignerExecutionAttribute.ENABLE_CHUNKED_ENCODING, true);
SdkHttpFullRequest signedRequest = s3V4aSigner.sign(testCase.requestBuilder.build(), executionAttributes);
verifyUnsignedPayload(signedRequest);
}
@Test
public void presigning_returns_signed_params() {
SdkHttpFullRequest signedPresignedRequest = SignerTestUtils.createPresignedPayloadHttpRequest("data");
when(signerAdapter.signRequest(any(), any())).thenReturn(signedPresignedRequest);
SigningTestCase testCase = SignerTestUtils.createBasicQuerySigningTestCase();
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
SdkHttpFullRequest request = testCase.requestBuilder.build();
SdkHttpFullRequest signed = s3V4aSigner.presign(request, executionAttributes);
assertThat(signed.rawQueryParameters().get("X-Amz-Signature").get(0)).isEqualTo("signature");
}
@Test
public void defaultAwsCrtS3V4aSigner_resolves_to_correct_signing_method(){
ExecutionAttributes executionAttributes = Mockito.mock(ExecutionAttributes.class);
AwsCredentials awsCredentials = Mockito.mock(AwsCredentials.class);
when(executionAttributes.getOptionalAttribute(ENABLE_PAYLOAD_SIGNING)).thenReturn(Optional.of(false));
when(executionAttributes.getOptionalAttribute(ENABLE_CHUNKED_ENCODING)).thenReturn(Optional.of(true));
SigningMethod signingMethod = SignerMethodResolver.resolveSigningMethodUsed(DefaultAwsCrtS3V4aSigner.create(),
executionAttributes,
awsCredentials);
assertThat(signingMethod).isEqualTo(SigningMethod.PROTOCOL_STREAMING_SIGNING_AUTH);
}
private void verifyUnsignedPayload(SdkHttpFullRequest signedRequest) {
verifyUnsignedHeaderRequest(signedRequest);
Mockito.verify(signerAdapter).signRequest(any(), configCaptor.capture());
AwsSigningConfig usedConfig = configCaptor.getValue();
assertThat(usedConfig.getSignedBodyValue()).isEqualTo(AwsSigningConfig.AwsSignedBodyValue.UNSIGNED_PAYLOAD);
}
private void verifyUnsignedPayloadWithTrailerChecksum(SdkHttpFullRequest signedRequest) {
verifyUnsignedHeaderRequest(signedRequest);
Mockito.verify(signerAdapter).signRequest(any(), configCaptor.capture());
AwsSigningConfig usedConfig = configCaptor.getValue();
assertThat(usedConfig.getSignedBodyValue()).isEqualTo("STREAMING-UNSIGNED-PAYLOAD-TRAILER");
}
private void verifyUnsignedHeaderRequest(SdkHttpFullRequest signedRequest) {
assertThat(signedRequest.firstMatchingHeader("Authorization")).isPresent();
assertThat(signedRequest.firstMatchingHeader("x-amz-decoded-content-length")).isNotPresent();
assertThat(signedRequest.contentStreamProvider()).isPresent();
assertThat(signedRequest.contentStreamProvider().get().newStream()).isNotInstanceOf(AwsSignedChunkedEncodingInputStream.class);
}
private void verifySignedPayload(SdkHttpFullRequest signedRequest) {
verifySignedRequestHeaders(signedRequest);
verifySignedBody(AwsSigningConfig.AwsSignedBodyValue.STREAMING_AWS4_ECDSA_P256_SHA256_PAYLOAD);
}
private void verifySignedChecksumPayload(SdkHttpFullRequest signedRequest) {
verifySignedRequestHeaders(signedRequest);
verifySignedBody(AwsSigningConfig.AwsSignedBodyValue.STREAMING_AWS4_ECDSA_P256_SHA256_PAYLOAD_TRAILER);
}
private void verifySignedBody(String awsSignedBodyValue) {
Mockito.verify(signerAdapter).sign(any(), configCaptor.capture());
AwsSigningConfig usedConfig = configCaptor.getValue();
assertThat(usedConfig.getSignedBodyValue()).isEqualTo(awsSignedBodyValue);
}
private void verifySignedRequestHeaders(SdkHttpFullRequest signedRequest) {
assertThat(signedRequest.firstMatchingHeader("Authorization")).isPresent();
assertThat(signedRequest.firstMatchingHeader("Content-Length")).isPresent();
assertThat(signedRequest.firstMatchingHeader("x-amz-decoded-content-length")).isPresent();
assertThat(signedRequest.contentStreamProvider()).isPresent();
assertThat(signedRequest.contentStreamProvider().get().newStream()).isInstanceOf(AwsSignedChunkedEncodingInputStream.class);
}
}
| 1,525 |
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/AwsCrtV4aSignerSigningScopeTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.auth.signer.AwsSignerExecutionAttribute;
import software.amazon.awssdk.authcrt.signer.AwsCrtV4aSigner;
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.http.SdkHttpFullRequest;
import software.amazon.awssdk.regions.RegionScope;
public class AwsCrtV4aSignerSigningScopeTest extends BaseSigningScopeTest {
@Override
protected SdkHttpFullRequest signRequestWithScope(SigningTestCase testCase, RegionScope defaultRegionScope,
RegionScope regionScope) {
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
if (regionScope != null) {
executionAttributes.putAttribute(AwsSignerExecutionAttribute.SIGNING_REGION_SCOPE, regionScope);
}
SdkHttpFullRequest request = testCase.requestBuilder.build();
return AwsCrtV4aSigner.builder().defaultRegionScope(defaultRegionScope).build().sign(request, executionAttributes);
}
@Override
protected SdkHttpFullRequest presignRequestWithScope(SigningTestCase testCase, RegionScope defaultRegionScope,
RegionScope regionScope) {
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
if (regionScope != null) {
executionAttributes.putAttribute(AwsSignerExecutionAttribute.SIGNING_REGION_SCOPE, regionScope);
}
SdkHttpFullRequest request = testCase.requestBuilder.build();
return AwsCrtV4aSigner.builder().defaultRegionScope(defaultRegionScope).build().presign(request, executionAttributes);
}
}
| 1,526 |
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¶m2=value2-1¶m2=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,527 |
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,528 |
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,529 |
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,530 |
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,531 |
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,532 |
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,533 |
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,534 |
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,535 |
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,536 |
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,537 |
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,538 |
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,539 |
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,540 |
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,541 |
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,542 |
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,543 |
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,544 |
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,545 |
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,546 |
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,547 |
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,548 |
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,549 |
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,550 |
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,551 |
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,552 |
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,553 |
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,554 |
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,555 |
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,556 |
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,557 |
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,558 |
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,559 |
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,560 |
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,561 |
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,562 |
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,563 |
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,564 |
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,565 |
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,566 |
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,567 |
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,568 |
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,569 |
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,570 |
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,571 |
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,572 |
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,573 |
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,574 |
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,575 |
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,576 |
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,577 |
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,578 |
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,579 |
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,580 |
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,581 |
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,582 |
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,583 |
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,584 |
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,585 |
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,586 |
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,587 |
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,588 |
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,589 |
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,590 |
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,591 |
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,592 |
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,593 |
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,594 |
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,595 |
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,596 |
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,597 |
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,598 |
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,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.