index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal/unmarshall/AwsQueryResponseHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.query.internal.unmarshall; import static software.amazon.awssdk.awscore.util.AwsHeader.AWS_REQUEST_ID; import java.io.IOException; import java.util.Map; import java.util.function.Function; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.AwsResponse; import software.amazon.awssdk.awscore.AwsResponseMetadata; import software.amazon.awssdk.awscore.DefaultAwsResponseMetadata; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.SdkStandardLogger; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Pair; /** * Response handler for AWS/Query services and Amazon EC2 which is a dialect of the Query protocol. * * @param <T> Indicates the type being unmarshalled by this response handler. */ @SdkInternalApi public final class AwsQueryResponseHandler<T extends AwsResponse> implements HttpResponseHandler<T> { private static final Logger log = Logger.loggerFor(AwsQueryResponseHandler.class); private final QueryProtocolUnmarshaller unmarshaller; private final Function<SdkHttpFullResponse, SdkPojo> pojoSupplier; public AwsQueryResponseHandler(QueryProtocolUnmarshaller unmarshaller, Function<SdkHttpFullResponse, SdkPojo> pojoSupplier) { this.unmarshaller = unmarshaller; this.pojoSupplier = pojoSupplier; } @Override public T handle(SdkHttpFullResponse response, ExecutionAttributes executionAttributes) throws Exception { try { return unmarshallResponse(response); } finally { response.content().ifPresent(i -> { try { i.close(); } catch (IOException e) { log.warn(() -> "Error closing HTTP content.", e); } }); } } @SuppressWarnings("unchecked") private T unmarshallResponse(SdkHttpFullResponse response) throws Exception { SdkStandardLogger.REQUEST_LOGGER.trace(() -> "Parsing service response XML."); Pair<T, Map<String, String>> result = unmarshaller.unmarshall(pojoSupplier.apply(response), response); SdkStandardLogger.REQUEST_LOGGER.trace(() -> "Done parsing service response."); AwsResponseMetadata responseMetadata = generateResponseMetadata(response, result.right()); return (T) result.left().toBuilder().responseMetadata(responseMetadata).build(); } /** * Create the default {@link AwsResponseMetadata}. This might be wrapped by a service * specific metadata object to provide modeled access to additional metadata. (See S3 and Kinesis). */ private AwsResponseMetadata generateResponseMetadata(SdkHttpResponse response, Map<String, String> metadata) { if (!metadata.containsKey(AWS_REQUEST_ID)) { metadata.put(AWS_REQUEST_ID, response.firstMatchingHeader(X_AMZN_REQUEST_ID_HEADERS).orElse(null)); } response.forEachHeader((key, value) -> metadata.put(key, value.get(0))); return DefaultAwsResponseMetadata.create(metadata); } @Override public boolean needsConnectionLeftOpen() { // Query doesn't support streaming so this is always false return false; } }
2,500
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal/unmarshall/SimpleTypeQueryUnmarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.query.internal.unmarshall; import java.util.List; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.protocols.core.StringToValueConverter; import software.amazon.awssdk.protocols.query.unmarshall.XmlElement; /** * Unmarshaller implementation for simple, scalar values. * * @param <T> Type being unmarshalled. */ @SdkInternalApi public final class SimpleTypeQueryUnmarshaller<T> implements QueryUnmarshaller<T> { private final StringToValueConverter.StringToValue<T> stringToValue; public SimpleTypeQueryUnmarshaller(StringToValueConverter.StringToValue<T> stringToValue) { this.stringToValue = stringToValue; } @Override public T unmarshall(QueryUnmarshallerContext context, List<XmlElement> content, SdkField<T> field) { if (content == null) { return null; } return stringToValue.convert(content.get(0).textContent(), field); } }
2,501
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal/marshall/SimpleTypeQueryMarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.query.internal.marshall; import java.time.Instant; import java.util.Collections; import java.util.EnumMap; import java.util.Map; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.protocol.MarshallLocation; import software.amazon.awssdk.core.traits.TimestampFormatTrait; import software.amazon.awssdk.protocols.core.InstantToString; import software.amazon.awssdk.protocols.core.StringToValueConverter.StringToValue; import software.amazon.awssdk.protocols.core.ValueToStringConverter; /** * Simple implementation of {@link QueryMarshaller} that converts a given value to a string using * {@link StringToValue} and emits it as a query param. * * @param <T> Type being marshalled. */ @SdkInternalApi public final class SimpleTypeQueryMarshaller<T> implements QueryMarshaller<T> { public static final QueryMarshaller<String> STRING = new SimpleTypeQueryMarshaller<>(ValueToStringConverter.FROM_STRING); public static final QueryMarshaller<Integer> INTEGER = new SimpleTypeQueryMarshaller<>(ValueToStringConverter.FROM_INTEGER); public static final QueryMarshaller<Float> FLOAT = new SimpleTypeQueryMarshaller<>(ValueToStringConverter.FROM_FLOAT); public static final QueryMarshaller<Boolean> BOOLEAN = new SimpleTypeQueryMarshaller<>(ValueToStringConverter.FROM_BOOLEAN); public static final QueryMarshaller<Double> DOUBLE = new SimpleTypeQueryMarshaller<>(ValueToStringConverter.FROM_DOUBLE); public static final QueryMarshaller<Long> LONG = new SimpleTypeQueryMarshaller<>(ValueToStringConverter.FROM_LONG); public static final QueryMarshaller<Short> SHORT = new SimpleTypeQueryMarshaller<>(ValueToStringConverter.FROM_SHORT); public static final QueryMarshaller<Instant> INSTANT = new SimpleTypeQueryMarshaller<>(InstantToString.create(defaultTimestampFormats())); public static final QueryMarshaller<SdkBytes> SDK_BYTES = new SimpleTypeQueryMarshaller<>(ValueToStringConverter.FROM_SDK_BYTES); public static final QueryMarshaller<Void> NULL = (request, path, val, sdkField) -> { }; private final ValueToStringConverter.ValueToString<T> valueToString; private SimpleTypeQueryMarshaller(ValueToStringConverter.ValueToString<T> valueToString) { this.valueToString = valueToString; } @Override public void marshall(QueryMarshallerContext context, String path, T val, SdkField<T> sdkField) { context.request().putRawQueryParameter(path, valueToString.convert(val, sdkField)); } /** * @return Default timestamp formats for each location supported by the Query protocol. */ public static Map<MarshallLocation, TimestampFormatTrait.Format> defaultTimestampFormats() { Map<MarshallLocation, TimestampFormatTrait.Format> formats = new EnumMap<>(MarshallLocation.class); // Query doesn't support location traits formats.put(MarshallLocation.PAYLOAD, TimestampFormatTrait.Format.ISO_8601); return Collections.unmodifiableMap(formats); } }
2,502
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal/marshall/QueryMarshallerContext.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.query.internal.marshall; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.protocols.core.ProtocolMarshaller; import software.amazon.awssdk.protocols.query.internal.unmarshall.QueryProtocolUnmarshaller; /** * Dependencies needed by {@link QueryProtocolUnmarshaller}. */ @SdkInternalApi public final class QueryMarshallerContext { private final QueryProtocolMarshaller protocolHandler; private final QueryMarshallerRegistry marshallerRegistry; private final SdkHttpFullRequest.Builder request; private QueryMarshallerContext(Builder builder) { this.protocolHandler = builder.protocolHandler; this.marshallerRegistry = builder.marshallerRegistry; this.request = builder.request; } /** * @return Implementation of {@link ProtocolMarshaller} that can be used to call back out to marshall structured data (i.e. * lists of objects). */ public QueryProtocolMarshaller protocolHandler() { return protocolHandler; } /** * @return Marshaller registry to obtain marshaller implementations for nested types (i.e. lists of objects or maps of string * to string). */ public QueryMarshallerRegistry marshallerRegistry() { return marshallerRegistry; } /** * @return Mutable {@link SdkHttpFullRequest.Builder} object that can be used to add headers, query params, * modify request URI, etc. */ public SdkHttpFullRequest.Builder request() { return request; } /** * @return Builder instance to construct a {@link QueryMarshallerContext}. */ public static Builder builder() { return new Builder(); } /** * Builder for a {@link QueryMarshallerContext}. */ public static final class Builder { private QueryProtocolMarshaller protocolHandler; private QueryMarshallerRegistry marshallerRegistry; private SdkHttpFullRequest.Builder request; private Builder() { } public Builder protocolHandler(QueryProtocolMarshaller protocolHandler) { this.protocolHandler = protocolHandler; return this; } public Builder marshallerRegistry(QueryMarshallerRegistry marshallerRegistry) { this.marshallerRegistry = marshallerRegistry; return this; } public Builder request(SdkHttpFullRequest.Builder request) { this.request = request; return this; } /** * @return An immutable {@link QueryMarshallerContext} object. */ public QueryMarshallerContext build() { return new QueryMarshallerContext(this); } } }
2,503
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal/marshall/QueryMarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.query.internal.marshall; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.protocols.core.Marshaller; /** * Interface for marshallers for AWS/Query protocol. * * @param <T> Type being marshalled. */ @FunctionalInterface @SdkInternalApi public interface QueryMarshaller<T> extends Marshaller<T> { void marshall(QueryMarshallerContext context, String path, T val, SdkField<T> sdkField); }
2,504
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal/marshall/ListQueryMarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.query.internal.marshall; import java.util.List; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.traits.ListTrait; import software.amazon.awssdk.core.util.SdkAutoConstructList; /** * Marshaller for list types. */ @SdkInternalApi public class ListQueryMarshaller implements QueryMarshaller<List<?>> { private final PathResolver pathResolver; private ListQueryMarshaller(PathResolver pathResolver) { this.pathResolver = pathResolver; } @Override public void marshall(QueryMarshallerContext context, String path, List<?> val, SdkField<List<?>> sdkField) { // Explicitly empty lists are marshalled as a query param with empty value in AWS/Query if (val.isEmpty() && !(val instanceof SdkAutoConstructList)) { context.request().putRawQueryParameter(path, ""); return; } for (int i = 0; i < val.size(); i++) { ListTrait listTrait = sdkField.getTrait(ListTrait.class); String listPath = pathResolver.resolve(path, i, listTrait); QueryMarshaller<Object> marshaller = context.marshallerRegistry().getMarshaller( ((SdkField<?>) listTrait.memberFieldInfo()).marshallingType(), val); marshaller.marshall(context, listPath, val.get(i), listTrait.memberFieldInfo()); } } @FunctionalInterface private interface PathResolver { String resolve(String path, int i, ListTrait listTrait); } /** * Wires up the {@link ListQueryMarshaller} with a {@link PathResolver} that respects the flattened trait. * * @return ListQueryMarshaller. */ public static ListQueryMarshaller awsQuery() { return new ListQueryMarshaller((path, i, listTrait) -> listTrait.isFlattened() ? String.format("%s.%d", path, i + 1) : String.format("%s.%s.%d", path, listTrait.memberFieldInfo().locationName(), i + 1)); } /** * Wires up the {@link ListQueryMarshaller} with a {@link PathResolver} that always flattens lists. The EC2 protocol * always flattens lists for inputs even when the 'flattened' trait is not present. * * @return ListQueryMarshaller. */ public static ListQueryMarshaller ec2Query() { return new ListQueryMarshaller((path, i, listTrait) -> String.format("%s.%d", path, i + 1)); } }
2,505
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal/marshall/QueryMarshallerRegistry.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.query.internal.marshall; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.protocol.MarshallLocation; import software.amazon.awssdk.core.protocol.MarshallingType; import software.amazon.awssdk.protocols.core.AbstractMarshallingRegistry; /** * Marshaller registry for the AWS Query protocol. */ @SdkInternalApi public final class QueryMarshallerRegistry extends AbstractMarshallingRegistry { private QueryMarshallerRegistry(Builder builder) { super(builder); } @SuppressWarnings("unchecked") public <T> QueryMarshaller<Object> getMarshaller(T val) { MarshallingType<T> marshallingType = toMarshallingType(val); return (QueryMarshaller<Object>) get(MarshallLocation.PAYLOAD, marshallingType); } @SuppressWarnings("unchecked") public <T> QueryMarshaller<Object> getMarshaller(MarshallingType<T> marshallingType, Object val) { return (QueryMarshaller<Object>) get(MarshallLocation.PAYLOAD, val == null ? MarshallingType.NULL : marshallingType); } /** * @return Builder instance to construct a {@link AbstractMarshallingRegistry}. */ public static Builder builder() { return new Builder(); } public static class Builder extends AbstractMarshallingRegistry.Builder { private Builder() { } /** * Registers a marshaller of the given type. Since the Query protocol doesn't support location * constraints this uses the location 'PAYLOAD' to register. * * @param marshallingType Type of marshaller * @param marshaller Marshaller implementation. * @param <T> Type of marshaller being registered. * @return This builder for method chaining. */ public <T> Builder marshaller(MarshallingType<T> marshallingType, QueryMarshaller<T> marshaller) { register(MarshallLocation.PAYLOAD, marshallingType, marshaller); return this; } /** * @return An immutable {@link QueryMarshallerRegistry} object. */ public QueryMarshallerRegistry build() { return new QueryMarshallerRegistry(this); } } }
2,506
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal/marshall/MapQueryMarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.query.internal.marshall; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.traits.MapTrait; @SdkInternalApi public class MapQueryMarshaller implements QueryMarshaller<Map<String, ?>> { @Override public void marshall(QueryMarshallerContext context, String path, Map<String, ?> val, SdkField<Map<String, ?>> sdkField) { MapTrait mapTrait = sdkField.getTrait(MapTrait.class); AtomicInteger entryNum = new AtomicInteger(1); val.forEach((key, value) -> { String mapKeyPath = resolveMapPath(path, mapTrait, entryNum, mapTrait.keyLocationName()); context.request().putRawQueryParameter(mapKeyPath, key); String mapValuePath = resolveMapPath(path, mapTrait, entryNum, mapTrait.valueLocationName()); QueryMarshaller<Object> marshaller = context.marshallerRegistry() .getMarshaller(((SdkField<?>) mapTrait.valueFieldInfo()).marshallingType(), val); marshaller.marshall(context, mapValuePath, value, mapTrait.valueFieldInfo()); entryNum.incrementAndGet(); }); } private static String resolveMapPath(String path, MapTrait mapTrait, AtomicInteger entryNum, String s) { return mapTrait.isFlattened() ? String.format("%s.%d.%s", path, entryNum.get(), s) : String.format("%s.entry.%d.%s", path, entryNum.get(), s); } }
2,507
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal/marshall/QueryProtocolMarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.query.internal.marshall; import java.net.URI; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.protocol.MarshallingType; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.protocols.core.OperationInfo; import software.amazon.awssdk.protocols.core.ProtocolMarshaller; import software.amazon.awssdk.protocols.core.ProtocolUtils; /** * Implementation of {@link ProtocolMarshaller} for AWS Query services. */ @SdkInternalApi public final class QueryProtocolMarshaller implements ProtocolMarshaller<SdkHttpFullRequest> { private static final QueryMarshallerRegistry AWS_QUERY_MARSHALLER_REGISTRY = commonRegistry() .marshaller(MarshallingType.LIST, ListQueryMarshaller.awsQuery()) .build(); private static final QueryMarshallerRegistry EC2_QUERY_MARSHALLER_REGISTRY = commonRegistry() .marshaller(MarshallingType.LIST, ListQueryMarshaller.ec2Query()) .build(); private final SdkHttpFullRequest.Builder request; private final QueryMarshallerRegistry registry; private final URI endpoint; private QueryProtocolMarshaller(Builder builder) { this.endpoint = builder.endpoint; this.request = fillBasicRequestParams(builder.operationInfo); this.registry = builder.isEc2 ? EC2_QUERY_MARSHALLER_REGISTRY : AWS_QUERY_MARSHALLER_REGISTRY; } private SdkHttpFullRequest.Builder fillBasicRequestParams(OperationInfo operationInfo) { return ProtocolUtils.createSdkHttpRequest(operationInfo, endpoint) .encodedPath("") .putRawQueryParameter("Action", operationInfo.operationIdentifier()) .putRawQueryParameter("Version", operationInfo.apiVersion()); } @Override public SdkHttpFullRequest marshall(SdkPojo pojo) { QueryMarshallerContext context = QueryMarshallerContext.builder() .request(request) .protocolHandler(this) .marshallerRegistry(registry) .build(); doMarshall(null, context, pojo); return request.build(); } private void doMarshall(String path, QueryMarshallerContext context, SdkPojo pojo) { for (SdkField<?> sdkField : pojo.sdkFields()) { Object val = sdkField.getValueOrDefault(pojo); QueryMarshaller<Object> marshaller = registry.getMarshaller(sdkField.marshallingType(), val); marshaller.marshall(context, resolvePath(path, sdkField), val, (SdkField<Object>) sdkField); } } private static String resolvePath(String path, SdkField<?> sdkField) { return path == null ? sdkField.locationName() : path + "." + sdkField.locationName(); } private static QueryMarshallerRegistry.Builder commonRegistry() { return QueryMarshallerRegistry .builder() .marshaller(MarshallingType.STRING, SimpleTypeQueryMarshaller.STRING) .marshaller(MarshallingType.INTEGER, SimpleTypeQueryMarshaller.INTEGER) .marshaller(MarshallingType.FLOAT, SimpleTypeQueryMarshaller.FLOAT) .marshaller(MarshallingType.BOOLEAN, SimpleTypeQueryMarshaller.BOOLEAN) .marshaller(MarshallingType.DOUBLE, SimpleTypeQueryMarshaller.DOUBLE) .marshaller(MarshallingType.LONG, SimpleTypeQueryMarshaller.LONG) .marshaller(MarshallingType.SHORT, SimpleTypeQueryMarshaller.SHORT) .marshaller(MarshallingType.INSTANT, SimpleTypeQueryMarshaller.INSTANT) .marshaller(MarshallingType.SDK_BYTES, SimpleTypeQueryMarshaller.SDK_BYTES) .marshaller(MarshallingType.NULL, SimpleTypeQueryMarshaller.NULL) .marshaller(MarshallingType.MAP, new MapQueryMarshaller()) .marshaller(MarshallingType.SDK_POJO, (context, path, val, sdkField) -> context.protocolHandler().doMarshall(path, context, val)); } /** * @return New {@link Builder} instance. */ public static Builder builder() { return new Builder(); } /** * Builder for {@link QueryProtocolMarshaller}. */ public static final class Builder { private OperationInfo operationInfo; private boolean isEc2; private URI endpoint; /** * @param operationInfo Metadata about the operation like URI, HTTP method, etc. * @return This builder for method chaining. */ public Builder operationInfo(OperationInfo operationInfo) { this.operationInfo = operationInfo; return this; } /** * @param ec2 True if the service is EC2. EC2 has some slightly different behavior so we wire things up * a bit differently for it. * @return This builder for method chaining. */ public Builder isEc2(boolean ec2) { isEc2 = ec2; return this; } /** * @param endpoint Endpoint to set on the marshalled request. * @return This builder for method chaining. */ public Builder endpoint(URI endpoint) { this.endpoint = endpoint; return this; } /** * @return New instance of {@link QueryProtocolMarshaller}. */ public QueryProtocolMarshaller build() { return new QueryProtocolMarshaller(this); } } }
2,508
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/unmarshall/AwsXmlErrorProtocolUnmarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.query.unmarshall; import java.io.IOException; import java.util.List; import java.util.Optional; import java.util.function.Function; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.awscore.exception.AwsErrorDetails; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.protocols.core.ExceptionMetadata; import software.amazon.awssdk.protocols.query.internal.unmarshall.AwsXmlErrorUnmarshaller; import software.amazon.awssdk.utils.Pair; /** * Error unmarshaller for Query/EC2/XML based protocols. Some examples of error responses from * the various protocols are below. * * <h3>Legacy Query (SimpleDB/EC2)</h3> * <pre> * {@code * <Response> * <Errors> * <Error> * <Code>MissingParameter</Code> * <Message>The request must contain the parameter DomainName</Message> * <BoxUsage>0.0055590278</BoxUsage> * </Error> * </Errors> * <RequestID>ad3280dd-5ac1-efd1-b9b0-a86969a9234d</RequestID> * </Response> * } * </pre> * * <h3>Traditional Query/Rest-XML (Cloudfront)</h3> * <pre> * {@code * <ErrorResponse xmlns="http://cloudfront.amazonaws.com/doc/2017-10-30/"> * <Error> * <Type>Sender</Type> * <Code>MalformedInput</Code> * <Message>Invalid XML document</Message> * </Error> * <RequestId>7c8da4af-de44-11e8-a60e-1b2014315455</RequestId> * </ErrorResponse> * } * </pre> * * <h3>Amazon S3</h3> * <pre> * {@code * <Error> * <Code>NoSuchBucket</Code> * <Message>The specified bucket does not exist</Message> * <BucketName>flajdfadjfladjf</BucketName> * <RequestId>D9DBB9F267849CA3</RequestId> * <HostId>fn8B1fUvWzg7I3CIeMT4UMqCZDF4+QO1JlbOJlQAVOosACZsLWv/K2dapVncz34a2mArhp11PjI=</HostId> * </Error> * } * </pre> */ @SdkProtectedApi public final class AwsXmlErrorProtocolUnmarshaller implements HttpResponseHandler<AwsServiceException> { private final AwsXmlErrorUnmarshaller awsXmlErrorUnmarshaller; private final Function<XmlElement, Optional<XmlElement>> errorRootExtractor; private AwsXmlErrorProtocolUnmarshaller(Builder builder) { this.errorRootExtractor = builder.errorRootExtractor; this.awsXmlErrorUnmarshaller = AwsXmlErrorUnmarshaller.builder() .defaultExceptionSupplier(builder.defaultExceptionSupplier) .exceptions(builder.exceptions) .errorUnmarshaller(builder.errorUnmarshaller) .build(); } @Override public AwsServiceException handle(SdkHttpFullResponse response, ExecutionAttributes executionAttributes) { Pair<XmlElement, SdkBytes> xmlAndBytes = parseXml(response); XmlElement document = xmlAndBytes.left(); Optional<XmlElement> errorRoot = errorRootExtractor.apply(document); return awsXmlErrorUnmarshaller.unmarshall(document, errorRoot, Optional.of(xmlAndBytes.right()), response, executionAttributes); } /** * Parse the response content into an XML document. If we fail to read the content or the XML is malformed * we still return an empty {@link XmlElement} so that unmarshalling can proceed. In those failure * cases we can't parse out the error code so we'd unmarshall into a generic service exception. * * @param response HTTP response. * @return Pair of the parsed {@link XmlElement} and the raw bytes of the response. */ private Pair<XmlElement, SdkBytes> parseXml(SdkHttpFullResponse response) { SdkBytes bytes = getResponseBytes(response); try { return Pair.of(XmlDomParser.parse(bytes.asInputStream()), bytes); } catch (Exception e) { return Pair.of(XmlElement.empty(), bytes); } } /** * Buffers the response content into an {@link SdkBytes} object. Used to fill the {@link AwsErrorDetails}. If * an {@link IOException} occurs then this will return {@link #emptyXmlBytes()} so that unmarshalling can proceed. * * @param response HTTP response. * @return Raw bytes of response. */ private SdkBytes getResponseBytes(SdkHttpFullResponse response) { try { return response.content() .map(SdkBytes::fromInputStream) .orElseGet(this::emptyXmlBytes); } catch (Exception e) { return emptyXmlBytes(); } } /** * @return Dummy XML document to allow unmarshalling when response can't be read/parsed. */ private SdkBytes emptyXmlBytes() { return SdkBytes.fromUtf8String("<eof/>"); } /** * @return New Builder instance. */ public static Builder builder() { return new Builder(); } /** * Builder for {@link AwsXmlErrorProtocolUnmarshaller}. */ public static final class Builder { private List<ExceptionMetadata> exceptions; private Supplier<SdkPojo> defaultExceptionSupplier; private Function<XmlElement, Optional<XmlElement>> errorRootExtractor; private XmlErrorUnmarshaller errorUnmarshaller; private Builder() { } /** * List of {@link ExceptionMetadata} to represent the modeled exceptions for the service. * For AWS services the error type is a string representing the type of the modeled exception. * * @return This builder for method chaining. */ public Builder exceptions(List<ExceptionMetadata> exceptions) { this.exceptions = exceptions; return this; } /** * Default exception type if "error code" does not match any known modeled exception. This is the generated * base exception for the service (i.e. DynamoDbException). * * @return This builder for method chaining. */ public Builder defaultExceptionSupplier(Supplier<SdkPojo> defaultExceptionSupplier) { this.defaultExceptionSupplier = defaultExceptionSupplier; return this; } /** * Extracts the <Error/> element from the top level XML document. Different protocols have slightly * different formats for where the Error element is located. The error root of the XML document contains * the code, message and any modeled fields of the exception. See javadocs of * {@link AwsXmlErrorProtocolUnmarshaller} for examples. * * @param errorRootExtractor Function that extracts the <Error/> element from the root XML document. * @return This builder for method chaining. */ public Builder errorRootExtractor(Function<XmlElement, Optional<XmlElement>> errorRootExtractor) { this.errorRootExtractor = errorRootExtractor; return this; } /** * The unmarshaller to use. The unmarshaller only unmarshalls any modeled fields of the exception, * additional metadata is extracted by {@link AwsXmlErrorProtocolUnmarshaller}. * * @param errorUnmarshaller Error unmarshaller to use. * @return This builder for method chaining. */ public Builder errorUnmarshaller(XmlErrorUnmarshaller errorUnmarshaller) { this.errorUnmarshaller = errorUnmarshaller; return this; } /** * @return New instance of {@link AwsXmlErrorProtocolUnmarshaller}. */ public AwsXmlErrorProtocolUnmarshaller build() { return new AwsXmlErrorProtocolUnmarshaller(this); } } }
2,509
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/unmarshall/XmlElement.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.query.unmarshall; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.exception.SdkClientException; /** * Represents an element in an XML document. */ @SdkProtectedApi public final class XmlElement { private static final XmlElement EMPTY = XmlElement.builder().elementName("eof").build(); private final String elementName; private final HashMap<String, List<XmlElement>> childrenByElement; private final List<XmlElement> children; private final String textContent; private final Map<String, String> attributes; private XmlElement(Builder builder) { this.elementName = builder.elementName; this.childrenByElement = new HashMap<>(builder.childrenByElement); this.children = Collections.unmodifiableList(new ArrayList<>(builder.children)); this.textContent = builder.textContent; this.attributes = Collections.unmodifiableMap(new HashMap<>(builder.attributes)); } /** * @return Tag name of the element. */ public String elementName() { return elementName; } /** * @return The list of direct children of this element. May be empty. */ public List<XmlElement> children() { return children; } /** * @return The first child element of this element. Null if this element has no children. */ public XmlElement getFirstChild() { return children.isEmpty() ? null : children.get(0); } /** * Get all child elements by the given tag name. This only returns direct children elements. * * @param tagName Tag name of elements to retrieve. * @return List of elements or empty list of no elements found with given name. */ public List<XmlElement> getElementsByName(String tagName) { return childrenByElement.getOrDefault(tagName, Collections.emptyList()); } /** * Retrieves a single child element by tag name. If more than one element is found then this method will throw an exception. * * @param tagName Tag name of element to get. * @return XmlElement with the matching tag name or null if no element exists. * @throws SdkClientException If more than one element with the given tag name is found. */ public XmlElement getElementByName(String tagName) { List<XmlElement> elementsByName = getElementsByName(tagName); if (elementsByName.size() > 1) { throw SdkClientException.create( String.format("Did not expect more than one element with the name %s in the XML event %s", tagName, this.elementName)); } return elementsByName.size() == 1 ? elementsByName.get(0) : null; } /** * Retrieves a single child element by tag name. If more than one element is found then this method will throw an exception. * * @param tagName Tag name of element to get. * @return Fulfilled {@link Optional} of XmlElement with the matching tag name or empty {@link Optional} if no element exists. * @throws SdkClientException If more than one element with the given tag name is found. */ public Optional<XmlElement> getOptionalElementByName(String tagName) { return Optional.ofNullable(getElementByName(tagName)); } /** * @return Text content of this element. */ public String textContent() { return textContent; } /** * Retrieves an optional attribute by attribute name. */ public Optional<String> getOptionalAttributeByName(String attribute) { return Optional.ofNullable(attributes.get(attribute)); } /** * Retrieves the attributes associated with the element */ public Map<String, String> attributes() { return attributes; } /** * @return New {@link Builder} instance. */ public static Builder builder() { return new Builder(); } /** * @return An empty {@link XmlElement} (<eof/>). */ public static XmlElement empty() { return EMPTY; } /** * Builder for {@link XmlElement}. */ public static final class Builder { private String elementName; private final Map<String, List<XmlElement>> childrenByElement = new HashMap<>(); private final List<XmlElement> children = new ArrayList<>(); private String textContent = ""; private Map<String, String> attributes = new HashMap<>(); private Builder() { } public Builder elementName(String elementName) { this.elementName = elementName; return this; } public Builder addChildElement(XmlElement childElement) { this.childrenByElement.computeIfAbsent(childElement.elementName(), s -> new ArrayList<>()); this.childrenByElement.get(childElement.elementName()).add(childElement); this.children.add(childElement); return this; } public Builder textContent(String textContent) { this.textContent = textContent; return this; } public Builder attributes(Map<String, String> attributes) { this.attributes = attributes; return this; } public XmlElement build() { return new XmlElement(this); } } }
2,510
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/unmarshall/XmlErrorUnmarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.query.unmarshall; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.http.SdkHttpFullResponse; /** * Interface to unmarshall a AWS/QUERY or REST/XML error response. */ @SdkProtectedApi public interface XmlErrorUnmarshaller { /** * @param sdkPojo Builder for exception class to unmarshall. * @param resultRoot Parsed XML document of response. * @param response HTTP response. * @param <TypeT> Type being unmarshalled. * @return Unmarshalled exception */ <TypeT extends SdkPojo> TypeT unmarshall(SdkPojo sdkPojo, XmlElement resultRoot, SdkHttpFullResponse response); }
2,511
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query
Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/unmarshall/XmlDomParser.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.query.unmarshall; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.Attribute; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.utils.LookaheadInputStream; /** * Parses an XML document into a simple DOM like structure, {@link XmlElement}. */ @SdkProtectedApi public final class XmlDomParser { private static final ThreadLocal<XMLInputFactory> FACTORY = ThreadLocal.withInitial(XmlDomParser::createXmlInputFactory); private XmlDomParser() { } public static XmlElement parse(InputStream inputStream) { LookaheadInputStream stream = new LookaheadInputStream(inputStream); try { if (stream.peek() == -1) { return XmlElement.empty(); } XMLEventReader reader = FACTORY.get().createXMLEventReader(stream); XMLEvent nextEvent; // Skip ahead to the first start element do { nextEvent = reader.nextEvent(); } while (reader.hasNext() && !nextEvent.isStartElement()); return parseElement(nextEvent.asStartElement(), reader); } catch (IOException | XMLStreamException e) { throw SdkClientException.create("Could not parse XML response.", e); } } /** * Parse an XML elemnt and any nested elements by recursively calling this method. * * @param startElement Start element object containing element name. * @param reader XML reader to get more events. * @return Parsed {@link XmlElement}. */ private static XmlElement parseElement(StartElement startElement, XMLEventReader reader) throws XMLStreamException { XmlElement.Builder elementBuilder = XmlElement.builder() .elementName(startElement.getName().getLocalPart()); if (startElement.getAttributes().hasNext()) { parseAttributes(startElement, elementBuilder); } XMLEvent nextEvent; do { nextEvent = reader.nextEvent(); if (nextEvent.isStartElement()) { elementBuilder.addChildElement(parseElement(nextEvent.asStartElement(), reader)); } else if (nextEvent.isCharacters()) { elementBuilder.textContent(readText(reader, nextEvent.asCharacters().getData())); } } while (!nextEvent.isEndElement()); return elementBuilder.build(); } /** * Parse the attributes of the element. */ @SuppressWarnings("unchecked") private static void parseAttributes(StartElement startElement, XmlElement.Builder elementBuilder) { Iterator<Attribute> iterator = startElement.getAttributes(); Map<String, String> attributes = new HashMap<>(); iterator.forEachRemaining(a -> { String key = a.getName().getPrefix() + ":" + a.getName().getLocalPart(); attributes.put(key, a.getValue()); }); elementBuilder.attributes(attributes); } /** * Reads all characters until the next end element event. * * @param eventReader Reader to read from. * @param firstChunk Initial character data that's already been read. * @return String with all character data concatenated. */ private static String readText(XMLEventReader eventReader, String firstChunk) throws XMLStreamException { StringBuilder sb = new StringBuilder(firstChunk); while (true) { XMLEvent event = eventReader.peek(); if (event.isCharacters()) { eventReader.nextEvent(); sb.append(event.asCharacters().getData()); } else { return sb.toString(); } } } /** * Disables certain dangerous features that attempt to automatically fetch DTDs * * See <a href="https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet">OWASP XXE Cheat Sheet</a> */ private static XMLInputFactory createXmlInputFactory() { XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty(XMLInputFactory.SUPPORT_DTD, false); factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); return factory; } }
2,512
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/test/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/test/java/software/amazon/awssdk/protocols/xml/internal/unmarshall/AwsXmlUnmarshallingContextTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.xml.internal.unmarshall; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.internal.InternalCoreExecutionAttribute; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.protocols.query.unmarshall.XmlElement; @RunWith(MockitoJUnitRunner.class) public class AwsXmlUnmarshallingContextTest { private static final XmlElement XML_ELEMENT_1 = XmlElement.builder().elementName("one").build(); private static final XmlElement XML_ELEMENT_2 = XmlElement.builder().elementName("two").build(); private static final XmlElement XML_ERROR_ELEMENT_1 = XmlElement.builder().elementName("error-one").build(); private static final XmlElement XML_ERROR_ELEMENT_2 = XmlElement.builder().elementName("error-two").build(); private static final ExecutionAttributes EXECUTION_ATTRIBUTES_1 = new ExecutionAttributes().putAttribute(InternalCoreExecutionAttribute.EXECUTION_ATTEMPT, 1); private static final ExecutionAttributes EXECUTION_ATTRIBUTES_2 = new ExecutionAttributes().putAttribute(InternalCoreExecutionAttribute.EXECUTION_ATTEMPT, 2); @Mock private SdkHttpFullResponse mockSdkHttpFullResponse; private AwsXmlUnmarshallingContext minimal() { return AwsXmlUnmarshallingContext.builder().build(); } private AwsXmlUnmarshallingContext maximal() { return AwsXmlUnmarshallingContext.builder() .parsedXml(XML_ELEMENT_1) .parsedErrorXml(XML_ERROR_ELEMENT_1) .isResponseSuccess(true) .sdkHttpFullResponse(mockSdkHttpFullResponse) .executionAttributes(EXECUTION_ATTRIBUTES_1) .build(); } @Test public void builder_minimal() { AwsXmlUnmarshallingContext result = minimal(); assertThat(result.isResponseSuccess()).isNull(); assertThat(result.sdkHttpFullResponse()).isNull(); assertThat(result.parsedRootXml()).isNull(); assertThat(result.executionAttributes()).isNull(); assertThat(result.parsedErrorXml()).isNull(); } @Test public void builder_maximal() { AwsXmlUnmarshallingContext result = maximal(); assertThat(result.isResponseSuccess()).isTrue(); assertThat(result.sdkHttpFullResponse()).isEqualTo(mockSdkHttpFullResponse); assertThat(result.parsedRootXml()).isEqualTo(XML_ELEMENT_1); assertThat(result.executionAttributes()).isEqualTo(EXECUTION_ATTRIBUTES_1); assertThat(result.parsedErrorXml()).isEqualTo(XML_ERROR_ELEMENT_1); } @Test public void toBuilder_maximal() { assertThat(maximal().toBuilder().build()).isEqualTo(maximal()); } @Test public void toBuilder_minimal() { assertThat(minimal().toBuilder().build()).isEqualTo(minimal()); } @Test public void equals_maximal_positive() { assertThat(maximal()).isEqualTo(maximal()); } @Test public void equals_minimal() { assertThat(minimal()).isEqualTo(minimal()); } @Test public void equals_maximal_negative() { assertThat(maximal().toBuilder().isResponseSuccess(false).build()).isNotEqualTo(maximal()); assertThat(maximal().toBuilder().sdkHttpFullResponse(mock(SdkHttpFullResponse.class)).build()).isNotEqualTo(maximal()); assertThat(maximal().toBuilder().parsedXml(XML_ELEMENT_2).build()).isNotEqualTo(maximal()); assertThat(maximal().toBuilder().parsedErrorXml(XML_ERROR_ELEMENT_2).build()).isNotEqualTo(maximal()); assertThat(maximal().toBuilder().executionAttributes(EXECUTION_ATTRIBUTES_2).build()).isNotEqualTo(maximal()); } @Test public void hashcode_maximal_positive() { assertThat(maximal().hashCode()).isEqualTo(maximal().hashCode()); } @Test public void hashcode_minimal_positive() { assertThat(minimal().hashCode()).isEqualTo(minimal().hashCode()); } @Test public void hashcode_maximal_negative() { assertThat(maximal().toBuilder().isResponseSuccess(false).build().hashCode()) .isNotEqualTo(maximal().hashCode()); assertThat(maximal().toBuilder().sdkHttpFullResponse(mock(SdkHttpFullResponse.class)).build().hashCode()) .isNotEqualTo(maximal().hashCode()); assertThat(maximal().toBuilder().parsedXml(XML_ELEMENT_2).build().hashCode()) .isNotEqualTo(maximal().hashCode()); assertThat(maximal().toBuilder().parsedErrorXml(XML_ERROR_ELEMENT_2).build().hashCode()) .isNotEqualTo(maximal().hashCode()); assertThat(maximal().toBuilder().executionAttributes(EXECUTION_ATTRIBUTES_2).build().hashCode()) .isNotEqualTo(maximal().hashCode()); } }
2,513
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/test/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/test/java/software/amazon/awssdk/protocols/xml/internal/unmarshall/AwsXmlResponseHandlerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.xml.internal.unmarshall; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.awscore.util.AwsHeader.AWS_REQUEST_ID; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import software.amazon.awssdk.awscore.AwsResponse; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.http.AbortableInputStream; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.utils.ImmutableMap; public class AwsXmlResponseHandlerTest { @Test public void handleResponse_awsResponse_shouldAddResponseMetadata() throws Exception { HttpResponseHandler<FakeResponse> delegate = Mockito.mock(HttpResponseHandler.class); AwsXmlResponseHandler<FakeResponse> responseHandler = new AwsXmlResponseHandler<>(delegate); SdkHttpFullResponse response = new TestSdkHttpFullResponse(); ExecutionAttributes executionAttributes = new ExecutionAttributes(); FakeResponse fakeResponse = FakeResponse.builder().build(); Mockito.when(delegate.handle(response, executionAttributes)).thenReturn(fakeResponse); assertThat(responseHandler.handle(response, executionAttributes) .responseMetadata().requestId()).isEqualTo("1234"); } @Test public void handleResponse_nonAwsResponse_shouldReturnDirectly() throws Exception { HttpResponseHandler<SdkPojo> delegate = Mockito.mock(HttpResponseHandler.class); AwsXmlResponseHandler<SdkPojo> responseHandler = new AwsXmlResponseHandler<>(delegate); SdkHttpFullResponse response = new TestSdkHttpFullResponse(); ExecutionAttributes executionAttributes = new ExecutionAttributes(); FakeSdkPojo fakeResponse = new FakeSdkPojo(); Mockito.when(delegate.handle(response, executionAttributes)).thenReturn(fakeResponse); assertThat(responseHandler.handle(response, executionAttributes)).isEqualTo(fakeResponse); } private static final class FakeSdkPojo implements SdkPojo { @Override public List<SdkField<?>> sdkFields() { return Collections.emptyList(); } } private static final class FakeResponse extends AwsResponse { private FakeResponse(Builder builder) { super(builder); } @Override public Builder toBuilder() { return new Builder(); } @Override public List<SdkField<?>> sdkFields() { return Collections.emptyList(); } public static Builder builder() { return new Builder(); } private static final class Builder extends AwsResponse.BuilderImpl { @Override public FakeResponse build() { return new FakeResponse(this); } } } private static class TestSdkHttpFullResponse implements SdkHttpFullResponse { @Override public Builder toBuilder() { return null; } @Override public Optional<AbortableInputStream> content() { return Optional.empty(); } @Override public Optional<String> statusText() { return Optional.empty(); } @Override public int statusCode() { return 0; } @Override public Map<String, List<String>> headers() { return ImmutableMap.of(AWS_REQUEST_ID, Collections.singletonList("1234")); } } }
2,514
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/test/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/test/java/software/amazon/awssdk/protocols/xml/internal/unmarshall/DecorateErrorFromResponseBodyUnmarshallerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.xml.internal.unmarshall; import static org.assertj.core.api.Assertions.assertThat; import java.util.Optional; import java.util.function.Function; import org.junit.jupiter.api.Test; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.protocols.query.unmarshall.XmlElement; public class DecorateErrorFromResponseBodyUnmarshallerTest { private static final Function<XmlElement, Optional<XmlElement>> FAIL_TEST_ERROR_ROOT_LOCATOR = ignored -> { throw new RuntimeException("This function should not have been called"); }; @Test public void status200_noBody() { DecorateErrorFromResponseBodyUnmarshaller decorateErrorFromResponseBodyUnmarshaller = DecorateErrorFromResponseBodyUnmarshaller.of(FAIL_TEST_ERROR_ROOT_LOCATOR); SdkHttpFullResponse sdkHttpFullResponse = SdkHttpFullResponse.builder() .statusCode(200) .build(); AwsXmlUnmarshallingContext context = AwsXmlUnmarshallingContext.builder() .sdkHttpFullResponse(sdkHttpFullResponse) .build(); AwsXmlUnmarshallingContext result = decorateErrorFromResponseBodyUnmarshaller.apply(context); assertThat(result.isResponseSuccess()).isTrue(); assertThat(result.parsedErrorXml()).isNull(); } @Test public void status200_bodyWithNoError() { DecorateErrorFromResponseBodyUnmarshaller decorateErrorFromResponseBodyUnmarshaller = DecorateErrorFromResponseBodyUnmarshaller.of(FAIL_TEST_ERROR_ROOT_LOCATOR); SdkHttpFullResponse sdkHttpFullResponse = SdkHttpFullResponse.builder() .statusCode(200) .build(); XmlElement parsedBody = XmlElement.builder() .elementName("ValidResponse") .build(); AwsXmlUnmarshallingContext context = AwsXmlUnmarshallingContext.builder() .sdkHttpFullResponse(sdkHttpFullResponse) .parsedXml(parsedBody) .build(); AwsXmlUnmarshallingContext result = decorateErrorFromResponseBodyUnmarshaller.apply(context); assertThat(result.isResponseSuccess()).isTrue(); assertThat(result.parsedErrorXml()).isNull(); } @Test public void status200_bodyWithError() { DecorateErrorFromResponseBodyUnmarshaller decorateErrorFromResponseBodyUnmarshaller = DecorateErrorFromResponseBodyUnmarshaller.of(FAIL_TEST_ERROR_ROOT_LOCATOR); SdkHttpFullResponse sdkHttpFullResponse = SdkHttpFullResponse.builder() .statusCode(200) .build(); XmlElement parsedError = XmlElement.builder() .elementName("test-error") .build(); XmlElement parsedBody = XmlElement.builder() .elementName("Error") .addChildElement(parsedError) .build(); AwsXmlUnmarshallingContext context = AwsXmlUnmarshallingContext.builder() .sdkHttpFullResponse(sdkHttpFullResponse) .parsedXml(parsedBody) .build(); AwsXmlUnmarshallingContext result = decorateErrorFromResponseBodyUnmarshaller.apply(context); assertThat(result.isResponseSuccess()).isFalse(); assertThat(result.parsedErrorXml()).isSameAs(parsedBody); } @Test public void status500_noBody() { DecorateErrorFromResponseBodyUnmarshaller decorateErrorFromResponseBodyUnmarshaller = DecorateErrorFromResponseBodyUnmarshaller.of(xml -> xml.getOptionalElementByName("test-error")); SdkHttpFullResponse sdkHttpFullResponse = SdkHttpFullResponse.builder() .statusCode(500) .build(); AwsXmlUnmarshallingContext context = AwsXmlUnmarshallingContext.builder() .sdkHttpFullResponse(sdkHttpFullResponse) .build(); AwsXmlUnmarshallingContext result = decorateErrorFromResponseBodyUnmarshaller.apply(context); assertThat(result.isResponseSuccess()).isFalse(); assertThat(result.parsedErrorXml()).isNull(); } @Test public void status500_bodyWithNoError() { DecorateErrorFromResponseBodyUnmarshaller decorateErrorFromResponseBodyUnmarshaller = DecorateErrorFromResponseBodyUnmarshaller.of(xml -> xml.getOptionalElementByName("test-error")); SdkHttpFullResponse sdkHttpFullResponse = SdkHttpFullResponse.builder() .statusCode(500) .build(); XmlElement parsedBody = XmlElement.builder() .elementName("ValidResponse") .build(); AwsXmlUnmarshallingContext context = AwsXmlUnmarshallingContext.builder() .sdkHttpFullResponse(sdkHttpFullResponse) .parsedXml(parsedBody) .build(); AwsXmlUnmarshallingContext result = decorateErrorFromResponseBodyUnmarshaller.apply(context); assertThat(result.isResponseSuccess()).isFalse(); assertThat(result.parsedErrorXml()).isNull(); } @Test public void status500_bodyWithError() { DecorateErrorFromResponseBodyUnmarshaller decorateErrorFromResponseBodyUnmarshaller = DecorateErrorFromResponseBodyUnmarshaller.of(xml -> xml.getOptionalElementByName("test-error")); SdkHttpFullResponse sdkHttpFullResponse = SdkHttpFullResponse.builder() .statusCode(500) .build(); XmlElement parsedError = XmlElement.builder() .elementName("test-error") .build(); XmlElement parsedBody = XmlElement.builder() .elementName("Error") .addChildElement(parsedError) .build(); AwsXmlUnmarshallingContext context = AwsXmlUnmarshallingContext.builder() .sdkHttpFullResponse(sdkHttpFullResponse) .parsedXml(parsedBody) .build(); AwsXmlUnmarshallingContext result = decorateErrorFromResponseBodyUnmarshaller.apply(context); assertThat(result.isResponseSuccess()).isFalse(); assertThat(result.parsedErrorXml()).isSameAs(parsedError); } }
2,515
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/AwsS3ProtocolFactory.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.xml; import java.util.Optional; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.awscore.AwsResponse; import software.amazon.awssdk.core.Response; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.protocols.query.unmarshall.XmlElement; import software.amazon.awssdk.protocols.xml.internal.unmarshall.AwsXmlPredicatedResponseHandler; import software.amazon.awssdk.protocols.xml.internal.unmarshall.DecorateErrorFromResponseBodyUnmarshaller; /** * Factory to generate the various protocol handlers and generators to be used for communicating with * Amazon S3. S3 has some unique differences from typical REST/XML that warrant a custom protocol factory. */ @SdkProtectedApi public final class AwsS3ProtocolFactory extends AwsXmlProtocolFactory { private AwsS3ProtocolFactory(Builder builder) { super(builder); } /** * For Amazon S3, the Code, Message, and modeled fields are in the top level document. * * @param document Root XML document. * @return If error root is found than a fulfilled {@link Optional}, otherwise an empty one. */ @Override Optional<XmlElement> getErrorRoot(XmlElement document) { return Optional.of(document); } public static Builder builder() { return new Builder(); } /** * Builder for {@link AwsS3ProtocolFactory}. */ public static final class Builder extends AwsXmlProtocolFactory.Builder<Builder> { private Builder() { } @Override public AwsS3ProtocolFactory build() { return new AwsS3ProtocolFactory(this); } } @Override public <T extends AwsResponse> HttpResponseHandler<Response<T>> createCombinedResponseHandler( Supplier<SdkPojo> pojoSupplier, XmlOperationMetadata staxOperationMetadata) { return createErrorCouldBeInBodyResponseHandler(pojoSupplier, staxOperationMetadata); } private <T extends AwsResponse> HttpResponseHandler<Response<T>> createErrorCouldBeInBodyResponseHandler( Supplier<SdkPojo> pojoSupplier, XmlOperationMetadata staxOperationMetadata) { return new AwsXmlPredicatedResponseHandler<>(r -> pojoSupplier.get(), createResponseTransformer(pojoSupplier), createErrorTransformer(), DecorateErrorFromResponseBodyUnmarshaller.of(this::getErrorRoot), staxOperationMetadata.isHasStreamingSuccessResponse()); } }
2,516
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/AwsXmlProtocolFactory.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.xml; import static java.util.Collections.unmodifiableList; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.function.Function; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.awscore.AwsResponse; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.core.Response; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.http.MetricCollectingHttpResponseHandler; import software.amazon.awssdk.core.internal.http.CombinedResponseHandler; import software.amazon.awssdk.core.metrics.CoreMetric; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.protocols.core.ExceptionMetadata; import software.amazon.awssdk.protocols.core.OperationInfo; import software.amazon.awssdk.protocols.core.OperationMetadataAttribute; import software.amazon.awssdk.protocols.core.ProtocolMarshaller; import software.amazon.awssdk.protocols.query.unmarshall.AwsXmlErrorProtocolUnmarshaller; import software.amazon.awssdk.protocols.query.unmarshall.XmlElement; import software.amazon.awssdk.protocols.xml.internal.marshall.XmlGenerator; import software.amazon.awssdk.protocols.xml.internal.marshall.XmlProtocolMarshaller; import software.amazon.awssdk.protocols.xml.internal.unmarshall.AwsXmlErrorTransformer; import software.amazon.awssdk.protocols.xml.internal.unmarshall.AwsXmlResponseHandler; import software.amazon.awssdk.protocols.xml.internal.unmarshall.AwsXmlResponseTransformer; import software.amazon.awssdk.protocols.xml.internal.unmarshall.AwsXmlUnmarshallingContext; import software.amazon.awssdk.protocols.xml.internal.unmarshall.XmlProtocolUnmarshaller; import software.amazon.awssdk.protocols.xml.internal.unmarshall.XmlResponseHandler; /** * Factory to generate the various protocol handlers and generators to be used for * communicating with REST/XML services. */ @SdkProtectedApi public class AwsXmlProtocolFactory { /** * Attribute for configuring the XML namespace to include in the xmlns attribute of the root element. */ public static final OperationMetadataAttribute<String> XML_NAMESPACE_ATTRIBUTE = new OperationMetadataAttribute<>(String.class); /** * Some services like Route53 specifies the location for the request shape. This should be the root of the * generated xml document. * * Other services Cloudfront, s3 don't specify location param for the request shape. For them, this value will be null. */ public static final OperationMetadataAttribute<String> ROOT_MARSHALL_LOCATION_ATTRIBUTE = new OperationMetadataAttribute<>(String.class); private static final XmlProtocolUnmarshaller XML_PROTOCOL_UNMARSHALLER = XmlProtocolUnmarshaller.create(); private final List<ExceptionMetadata> modeledExceptions; private final Supplier<SdkPojo> defaultServiceExceptionSupplier; private final HttpResponseHandler<AwsServiceException> errorUnmarshaller; private final SdkClientConfiguration clientConfiguration; AwsXmlProtocolFactory(Builder<?> builder) { this.modeledExceptions = unmodifiableList(builder.modeledExceptions); this.defaultServiceExceptionSupplier = builder.defaultServiceExceptionSupplier; this.clientConfiguration = builder.clientConfiguration; this.errorUnmarshaller = timeUnmarshalling( AwsXmlErrorProtocolUnmarshaller.builder() .defaultExceptionSupplier(defaultServiceExceptionSupplier) .exceptions(modeledExceptions) .errorUnmarshaller(XML_PROTOCOL_UNMARSHALLER) .errorRootExtractor(this::getErrorRoot) .build()); } /** * Creates an instance of {@link XmlProtocolMarshaller} to be used for marshalling the request. * * @param operationInfo Info required to marshall the request */ public ProtocolMarshaller<SdkHttpFullRequest> createProtocolMarshaller(OperationInfo operationInfo) { return XmlProtocolMarshaller.builder() .endpoint(clientConfiguration.option(SdkClientOption.ENDPOINT)) .xmlGenerator(createGenerator(operationInfo)) .operationInfo(operationInfo) .build(); } public <T extends SdkPojo> HttpResponseHandler<T> createResponseHandler(Supplier<SdkPojo> pojoSupplier, XmlOperationMetadata staxOperationMetadata) { return createResponseHandler(r -> pojoSupplier.get(), staxOperationMetadata); } public <T extends SdkPojo> HttpResponseHandler<T> createResponseHandler(Function<SdkHttpFullResponse, SdkPojo> pojoSupplier, XmlOperationMetadata staxOperationMetadata) { return timeUnmarshalling( new AwsXmlResponseHandler<>( new XmlResponseHandler<>( XML_PROTOCOL_UNMARSHALLER, pojoSupplier, staxOperationMetadata.isHasStreamingSuccessResponse()))); } protected <T extends AwsResponse> Function<AwsXmlUnmarshallingContext, T> createResponseTransformer( Supplier<SdkPojo> pojoSupplier) { return new AwsXmlResponseTransformer<>( XML_PROTOCOL_UNMARSHALLER, r -> pojoSupplier.get()); } protected Function<AwsXmlUnmarshallingContext, AwsServiceException> createErrorTransformer() { return AwsXmlErrorTransformer.builder() .defaultExceptionSupplier(defaultServiceExceptionSupplier) .exceptions(modeledExceptions) .errorUnmarshaller(XML_PROTOCOL_UNMARSHALLER) .build(); } public HttpResponseHandler<AwsServiceException> createErrorResponseHandler() { return errorUnmarshaller; } private <T> MetricCollectingHttpResponseHandler<T> timeUnmarshalling(HttpResponseHandler<T> delegate) { return MetricCollectingHttpResponseHandler.create(CoreMetric.UNMARSHALLING_DURATION, delegate); } public <T extends AwsResponse> HttpResponseHandler<Response<T>> createCombinedResponseHandler( Supplier<SdkPojo> pojoSupplier, XmlOperationMetadata staxOperationMetadata) { return new CombinedResponseHandler<>(createResponseHandler(pojoSupplier, staxOperationMetadata), createErrorResponseHandler()); } /** * Extracts the <Error/> element from the root XML document. This method is protected as S3 has * a slightly different location. * * @param document Root XML document. * @return If error root is found than a fulfilled {@link Optional}, otherwise an empty one. */ Optional<XmlElement> getErrorRoot(XmlElement document) { return document.getOptionalElementByName("Error"); } private XmlGenerator createGenerator(OperationInfo operationInfo) { return operationInfo.hasPayloadMembers() ? XmlGenerator.create(operationInfo.addtionalMetadata(XML_NAMESPACE_ATTRIBUTE)) : null; } public static Builder builder() { return new Builder(); } /** * Builder for {@link AwsXmlProtocolFactory}. */ public static class Builder<SubclassT extends Builder> { private final List<ExceptionMetadata> modeledExceptions = new ArrayList<>(); private Supplier<SdkPojo> defaultServiceExceptionSupplier; private SdkClientConfiguration clientConfiguration; Builder() { } /** * Registers a new modeled exception by the error code. * * @param errorMetadata metadata for unmarshalling the exceptions * @return This builder for method chaining. */ public final SubclassT registerModeledException(ExceptionMetadata errorMetadata) { modeledExceptions.add(errorMetadata); return getSubclass(); } /** * A supplier for the services base exception builder. This is used when we can't identify any modeled * exception to unmarshall into. * * @param exceptionBuilderSupplier Suppplier of the base service exceptions Builder. * @return This builder for method chaining. */ public SubclassT defaultServiceExceptionSupplier(Supplier<SdkPojo> exceptionBuilderSupplier) { this.defaultServiceExceptionSupplier = exceptionBuilderSupplier; return getSubclass(); } /** * Sets the {@link SdkClientConfiguration} which contains the service endpoint. * * @param clientConfiguration Configuration of the client. * @return This builder for method chaining. */ public SubclassT clientConfiguration(SdkClientConfiguration clientConfiguration) { this.clientConfiguration = clientConfiguration; return getSubclass(); } @SuppressWarnings("unchecked") private SubclassT getSubclass() { return (SubclassT) this; } public AwsXmlProtocolFactory build() { return new AwsXmlProtocolFactory(this); } } }
2,517
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/XmlOperationMetadata.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.xml; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.protocols.xml.internal.unmarshall.AwsXmlResponseHandler; /** * Contains information needed to create a {@link AwsXmlResponseHandler} for the client. */ @NotThreadSafe @SdkProtectedApi public final class XmlOperationMetadata { private boolean hasStreamingSuccessResponse; public XmlOperationMetadata() { } private XmlOperationMetadata(Builder b) { this.hasStreamingSuccessResponse = b.hasStreamingSuccessResponse; } public boolean isHasStreamingSuccessResponse() { return hasStreamingSuccessResponse; } public XmlOperationMetadata withHasStreamingSuccessResponse(boolean hasStreamingSuccessResponse) { this.hasStreamingSuccessResponse = hasStreamingSuccessResponse; return this; } public static Builder builder() { return new Builder(); } public static class Builder { private boolean hasStreamingSuccessResponse; public Builder hasStreamingSuccessResponse(boolean hasStreamingSuccessResponse) { this.hasStreamingSuccessResponse = hasStreamingSuccessResponse; return this; } public XmlOperationMetadata build() { return new XmlOperationMetadata(this); } } }
2,518
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/unmarshall/AwsXmlPredicatedResponseHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.xml.internal.unmarshall; import static software.amazon.awssdk.core.SdkStandardLogger.logRequestId; import java.util.Optional; import java.util.function.Function; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.Response; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.exception.RetryableException; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.exception.SdkException; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.protocols.query.unmarshall.XmlElement; import software.amazon.awssdk.utils.IoUtils; /** * Unmarshalls an HTTP response into either a successful response POJO, or into a (possibly modeled) exception based * on a predicate that the unmarshalled response can be tested against. Returns a wrapper {@link Response} object which * may contain either the unmarshalled success POJO, or the unmarshalled exception. * * @param <OutputT> Type of successful unmarshalled POJO. */ @SdkInternalApi public class AwsXmlPredicatedResponseHandler<OutputT> implements HttpResponseHandler<Response<OutputT>> { private static final Logger log = LoggerFactory.getLogger(AwsXmlPredicatedResponseHandler.class); private final Function<SdkHttpFullResponse, SdkPojo> pojoSupplier; private final Function<AwsXmlUnmarshallingContext, OutputT> successResponseTransformer; private final Function<AwsXmlUnmarshallingContext, ? extends SdkException> errorResponseTransformer; private final Function<AwsXmlUnmarshallingContext, AwsXmlUnmarshallingContext> decorateContextWithError; private final boolean needsConnectionLeftOpen; /** * Standard constructor * @param pojoSupplier A method that supplies an empty builder of the correct type * @param successResponseTransformer A function that can unmarshall a response object from parsed XML * @param errorResponseTransformer A function that can unmarshall an exception object from parsed XML * @param decorateContextWithError A function that determines if the response was an error or not * @param needsConnectionLeftOpen true if the underlying connection should not be closed once parsed */ public AwsXmlPredicatedResponseHandler( Function<SdkHttpFullResponse, SdkPojo> pojoSupplier, Function<AwsXmlUnmarshallingContext, OutputT> successResponseTransformer, Function<AwsXmlUnmarshallingContext, ? extends SdkException> errorResponseTransformer, Function<AwsXmlUnmarshallingContext, AwsXmlUnmarshallingContext> decorateContextWithError, boolean needsConnectionLeftOpen) { this.pojoSupplier = pojoSupplier; this.successResponseTransformer = successResponseTransformer; this.errorResponseTransformer = errorResponseTransformer; this.decorateContextWithError = decorateContextWithError; this.needsConnectionLeftOpen = needsConnectionLeftOpen; } /** * Handle a response * @param httpResponse The HTTP response object * @param executionAttributes The attributes attached to this particular execution. * @return A wrapped response object with the unmarshalled result in it. */ @Override public Response<OutputT> handle(SdkHttpFullResponse httpResponse, ExecutionAttributes executionAttributes) { boolean didRequestFail = true; try { Response<OutputT> response = handleResponse(httpResponse, executionAttributes); didRequestFail = !response.isSuccess(); return response; } finally { closeInputStreamIfNeeded(httpResponse, didRequestFail); } } private Response<OutputT> handleResponse(SdkHttpFullResponse httpResponse, ExecutionAttributes executionAttributes) { AwsXmlUnmarshallingContext parsedResponse = parseResponse(httpResponse, executionAttributes); parsedResponse = decorateContextWithError.apply(parsedResponse); logRequestId(httpResponse); if (parsedResponse.isResponseSuccess()) { OutputT response = handleSuccessResponse(parsedResponse); return Response.<OutputT>builder().httpResponse(httpResponse) .response(response) .isSuccess(true) .build(); } else { return Response.<OutputT>builder().httpResponse(httpResponse) .exception(handleErrorResponse(parsedResponse)) .isSuccess(false) .build(); } } private AwsXmlUnmarshallingContext parseResponse(SdkHttpFullResponse httpFullResponse, ExecutionAttributes executionAttributes) { XmlElement document = XmlResponseParserUtils.parse(pojoSupplier.apply(httpFullResponse), httpFullResponse); return AwsXmlUnmarshallingContext.builder() .parsedXml(document) .executionAttributes(executionAttributes) .sdkHttpFullResponse(httpFullResponse) .build(); } /** * Handles a successful response from a service call by unmarshalling the results using the * specified response handler. * * @return The contents of the response, unmarshalled using the specified response handler. */ private OutputT handleSuccessResponse(AwsXmlUnmarshallingContext parsedResponse) { try { return successResponseTransformer.apply(parsedResponse); } catch (RetryableException e) { throw e; } catch (Exception e) { if (e instanceof SdkException && ((SdkException) e).retryable()) { throw (SdkException) e; } String errorMessage = "Unable to unmarshall response (" + e.getMessage() + "). Response Code: " + parsedResponse.sdkHttpFullResponse().statusCode() + ", Response Text: " + parsedResponse.sdkHttpFullResponse().statusText().orElse(null); throw SdkClientException.builder().message(errorMessage).cause(e).build(); } } /** * Responsible for handling an error response, including unmarshalling the error response * into the most specific exception type possible, and throwing the exception. */ private SdkException handleErrorResponse(AwsXmlUnmarshallingContext parsedResponse) { try { SdkException exception = errorResponseTransformer.apply(parsedResponse); exception.fillInStackTrace(); return exception; } catch (Exception e) { String errorMessage = String.format("Unable to unmarshall error response (%s). " + "Response Code: %d, Response Text: %s", e.getMessage(), parsedResponse.sdkHttpFullResponse().statusCode(), parsedResponse.sdkHttpFullResponse().statusText().orElse("null")); throw SdkClientException.builder().message(errorMessage).cause(e).build(); } } /** * Close the input stream if required. */ private void closeInputStreamIfNeeded(SdkHttpFullResponse httpResponse, boolean didRequestFail) { // Always close on failed requests. Close on successful requests unless it needs connection left open if (didRequestFail || !needsConnectionLeftOpen) { Optional.ofNullable(httpResponse) .flatMap(SdkHttpFullResponse::content) // If no content, no need to close .ifPresent(s -> IoUtils.closeQuietly(s, log)); } } }
2,519
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/unmarshall/DecorateErrorFromResponseBodyUnmarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.xml.internal.unmarshall; import java.util.Optional; import java.util.function.Function; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.protocols.query.unmarshall.XmlElement; /** * A function that decorates a {@link AwsXmlUnmarshallingContext} that already contains the parsed XML of the * response body with parsed error XML if the HTTP response status indicates failure or a serialized error is found * in the XML body of a 'successful' response. This is a non-standard error handling behavior that is used by some * non-streaming S3 operations. */ @SdkInternalApi public class DecorateErrorFromResponseBodyUnmarshaller implements Function<AwsXmlUnmarshallingContext, AwsXmlUnmarshallingContext> { private static final String ERROR_IN_SUCCESS_BODY_ELEMENT_NAME = "Error"; private final Function<XmlElement, Optional<XmlElement>> errorRootLocationFunction; private DecorateErrorFromResponseBodyUnmarshaller(Function<XmlElement, Optional<XmlElement>> errorRootLocationFunction) { this.errorRootLocationFunction = errorRootLocationFunction; } /** * Constructs a function that can be used to decorate a parsed error from a response if one is found. * @param errorRootFunction A function that can be used to locate the root of the serialized error in the XML * body if the HTTP status code of the response indicates an error. This function is not * applied for HTTP responses that indicate success, instead the root of the document * will always be checked for an element tagged 'Error'. * @return An unmarshalling function that will decorate the unmarshalling context with a parsed error if one is * found in the response. */ public static DecorateErrorFromResponseBodyUnmarshaller of(Function<XmlElement, Optional<XmlElement>> errorRootFunction) { return new DecorateErrorFromResponseBodyUnmarshaller(errorRootFunction); } @Override public AwsXmlUnmarshallingContext apply(AwsXmlUnmarshallingContext context) { Optional<XmlElement> parsedRootXml = Optional.ofNullable(context.parsedRootXml()); if (!context.sdkHttpFullResponse().isSuccessful()) { // Request was non-2xx, defer to protocol handler for error root Optional<XmlElement> parsedErrorXml = parsedRootXml.flatMap(errorRootLocationFunction); return context.toBuilder().isResponseSuccess(false).parsedErrorXml(parsedErrorXml.orElse(null)).build(); } // Check body to see if an error turned up there Optional<XmlElement> parsedErrorXml = parsedRootXml.isPresent() ? getErrorRootFromSuccessBody(context.parsedRootXml()) : Optional.empty(); // Request had an HTTP success code, but an error was found in the body return parsedErrorXml.map(xmlElement -> context.toBuilder() .isResponseSuccess(false) .parsedErrorXml(xmlElement) .build()) // Otherwise the response can be considered successful .orElseGet(() -> context.toBuilder() .isResponseSuccess(true) .build()); } private static Optional<XmlElement> getErrorRootFromSuccessBody(XmlElement document) { return ERROR_IN_SUCCESS_BODY_ELEMENT_NAME.equals(document.elementName()) ? Optional.of(document) : Optional.empty(); } }
2,520
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/unmarshall/XmlUnmarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.xml.internal.unmarshall; import java.util.List; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.protocols.query.unmarshall.XmlElement; /** * Interface to unmarshall response fields for Xml service * * @param <T> Type to unmarshall into */ @SdkInternalApi public interface XmlUnmarshaller<T> { T unmarshall(XmlUnmarshallerContext context, List<XmlElement> content, SdkField<T> field); }
2,521
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/unmarshall/AwsXmlResponseHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.xml.internal.unmarshall; import static software.amazon.awssdk.awscore.util.AwsHeader.AWS_REQUEST_ID; import java.util.HashMap; import java.util.Map; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.AwsResponse; import software.amazon.awssdk.awscore.AwsResponseMetadata; import software.amazon.awssdk.awscore.DefaultAwsResponseMetadata; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.http.SdkHttpResponse; /** * Response handler that adds {@link AwsResponseMetadata} to the response. * * @param <T> Indicates the type being unmarshalled by this response handler. */ @SdkInternalApi public final class AwsXmlResponseHandler<T> implements HttpResponseHandler<T> { private final HttpResponseHandler<T> delegate; public AwsXmlResponseHandler(HttpResponseHandler<T> responseHandler) { this.delegate = responseHandler; } @Override public T handle(SdkHttpFullResponse response, ExecutionAttributes executionAttributes) throws Exception { T result = delegate.handle(response, executionAttributes); if (result instanceof AwsResponse) { AwsResponseMetadata responseMetadata = generateResponseMetadata(response); return (T) ((AwsResponse) result).toBuilder().responseMetadata(responseMetadata).build(); } return result; } /** * Create the default {@link AwsResponseMetadata}. This might be wrapped by a service * specific metadata object to provide modeled access to additional metadata. (See S3 and Kinesis). */ private AwsResponseMetadata generateResponseMetadata(SdkHttpResponse response) { Map<String, String> metadata = new HashMap<>(); metadata.put(AWS_REQUEST_ID, response.firstMatchingHeader(X_AMZN_REQUEST_ID_HEADERS).orElse(null)); response.forEachHeader((key, value) -> metadata.put(key, value.get(0))); return DefaultAwsResponseMetadata.create(metadata); } @Override public boolean needsConnectionLeftOpen() { return delegate.needsConnectionLeftOpen(); } }
2,522
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/unmarshall/XmlUnmarshallerRegistry.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.xml.internal.unmarshall; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.protocol.MarshallLocation; import software.amazon.awssdk.core.protocol.MarshallingType; import software.amazon.awssdk.protocols.core.AbstractMarshallingRegistry; @SdkInternalApi public final class XmlUnmarshallerRegistry extends AbstractMarshallingRegistry { private XmlUnmarshallerRegistry(Builder builder) { super(builder); } @SuppressWarnings("unchecked") public <T> XmlUnmarshaller<Object> getUnmarshaller(MarshallLocation marshallLocation, MarshallingType<T> marshallingType) { return (XmlUnmarshaller<Object>) get(marshallLocation, marshallingType); } /** * @return Builder instance to construct a {@link XmlUnmarshallerRegistry}. */ public static Builder builder() { return new Builder(); } /** * Builder for a {@link XmlUnmarshallerRegistry}. */ public static final class Builder extends AbstractMarshallingRegistry.Builder { private Builder() { } public <T> Builder payloadUnmarshaller(MarshallingType<T> marshallingType, XmlUnmarshaller<T> marshaller) { register(MarshallLocation.PAYLOAD, marshallingType, marshaller); return this; } public <T> Builder headerUnmarshaller(MarshallingType<T> marshallingType, XmlUnmarshaller<T> marshaller) { register(MarshallLocation.HEADER, marshallingType, marshaller); return this; } public <T> Builder statusCodeUnmarshaller(MarshallingType<T> marshallingType, XmlUnmarshaller<T> marshaller) { register(MarshallLocation.STATUS_CODE, marshallingType, marshaller); return this; } /** * @return An immutable {@link XmlUnmarshallerRegistry} object. */ public XmlUnmarshallerRegistry build() { return new XmlUnmarshallerRegistry(this); } } }
2,523
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/unmarshall/HeaderUnmarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.xml.internal.unmarshall; import static software.amazon.awssdk.utils.StringUtils.replacePrefixIgnoreCase; import static software.amazon.awssdk.utils.StringUtils.startsWithIgnoreCase; import java.time.Instant; import java.util.HashMap; import java.util.List; import java.util.Map; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.protocols.core.StringToValueConverter; import software.amazon.awssdk.protocols.query.unmarshall.XmlElement; @SdkInternalApi public final class HeaderUnmarshaller { public static final XmlUnmarshaller<String> STRING = new SimpleHeaderUnmarshaller<>(StringToValueConverter.TO_STRING); public static final XmlUnmarshaller<Integer> INTEGER = new SimpleHeaderUnmarshaller<>(StringToValueConverter.TO_INTEGER); public static final XmlUnmarshaller<Long> LONG = new SimpleHeaderUnmarshaller<>(StringToValueConverter.TO_LONG); public static final XmlUnmarshaller<Short> SHORT = new SimpleHeaderUnmarshaller<>(StringToValueConverter.TO_SHORT); public static final XmlUnmarshaller<Float> FLOAT = new SimpleHeaderUnmarshaller<>(StringToValueConverter.TO_FLOAT); public static final XmlUnmarshaller<Double> DOUBLE = new SimpleHeaderUnmarshaller<>(StringToValueConverter.TO_DOUBLE); public static final XmlUnmarshaller<Boolean> BOOLEAN = new SimpleHeaderUnmarshaller<>(StringToValueConverter.TO_BOOLEAN); public static final XmlUnmarshaller<Instant> INSTANT = new SimpleHeaderUnmarshaller<>(XmlProtocolUnmarshaller.INSTANT_STRING_TO_VALUE); // Only supports string value type public static final XmlUnmarshaller<Map<String, ?>> MAP = ((context, content, field) -> { Map<String, String> result = new HashMap<>(); context.response().forEachHeader((name, value) -> { if (startsWithIgnoreCase(name, field.locationName())) { result.put(replacePrefixIgnoreCase(name, field.locationName(), ""), String.join(",", value)); } }); return result; }); // Only supports string value type public static final XmlUnmarshaller<List<?>> LIST = (context, content, field) -> context.response().matchingHeaders(field.locationName()); private HeaderUnmarshaller() { } private static class SimpleHeaderUnmarshaller<T> implements XmlUnmarshaller<T> { private final StringToValueConverter.StringToValue<T> stringToValue; private SimpleHeaderUnmarshaller(StringToValueConverter.StringToValue<T> stringToValue) { this.stringToValue = stringToValue; } @Override public T unmarshall(XmlUnmarshallerContext context, List<XmlElement> content, SdkField<T> field) { return context.response().firstMatchingHeader(field.locationName()) .map(s -> stringToValue.convert(s, field)) .orElse(null); } } }
2,524
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/unmarshall/AwsXmlResponseTransformer.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.xml.internal.unmarshall; import static software.amazon.awssdk.awscore.util.AwsHeader.AWS_REQUEST_ID; import java.util.HashMap; import java.util.Map; import java.util.function.Function; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.AwsResponse; import software.amazon.awssdk.awscore.AwsResponseMetadata; import software.amazon.awssdk.awscore.DefaultAwsResponseMetadata; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.SdkStandardLogger; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.protocols.query.unmarshall.XmlElement; /** * A transformer function that takes a parsed XML response and converts it into an {@link AwsResponse}. Used * as a component in the {@link AwsXmlPredicatedResponseHandler}. */ @SdkInternalApi public final class AwsXmlResponseTransformer<T extends AwsResponse> implements Function<AwsXmlUnmarshallingContext, T> { private static final String X_AMZN_REQUEST_ID_HEADER = "x-amzn-RequestId"; private final XmlProtocolUnmarshaller unmarshaller; private final Function<SdkHttpFullResponse, SdkPojo> pojoSupplier; public AwsXmlResponseTransformer(XmlProtocolUnmarshaller unmarshaller, Function<SdkHttpFullResponse, SdkPojo> pojoSupplier) { this.unmarshaller = unmarshaller; this.pojoSupplier = pojoSupplier; } @Override public T apply(AwsXmlUnmarshallingContext context) { return unmarshallResponse(context.sdkHttpFullResponse(), context.parsedRootXml()); } @SuppressWarnings("unchecked") private T unmarshallResponse(SdkHttpFullResponse response, XmlElement parsedXml) { SdkStandardLogger.REQUEST_LOGGER.trace(() -> "Unmarshalling parsed service response XML."); T result = unmarshaller.unmarshall(pojoSupplier.apply(response), parsedXml, response); SdkStandardLogger.REQUEST_LOGGER.trace(() -> "Done unmarshalling parsed service response."); AwsResponseMetadata responseMetadata = generateResponseMetadata(response); return (T) result.toBuilder().responseMetadata(responseMetadata).build(); } /** * Create the default {@link AwsResponseMetadata}. This might be wrapped by a service * specific metadata object to provide modeled access to additional metadata. (See S3 and Kinesis). */ private AwsResponseMetadata generateResponseMetadata(SdkHttpResponse response) { Map<String, String> metadata = new HashMap<>(); metadata.put(AWS_REQUEST_ID, response.firstMatchingHeader(X_AMZN_REQUEST_ID_HEADER).orElse(null)); response.forEachHeader((key, value) -> metadata.put(key, value.get(0))); return DefaultAwsResponseMetadata.create(metadata); } }
2,525
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/unmarshall/XmlPayloadUnmarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.xml.internal.unmarshall; import static java.util.Collections.singletonList; import java.math.BigDecimal; import java.time.Instant; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.traits.ListTrait; import software.amazon.awssdk.core.traits.MapTrait; import software.amazon.awssdk.protocols.core.StringToValueConverter; import software.amazon.awssdk.protocols.query.unmarshall.XmlElement; @SdkInternalApi public final class XmlPayloadUnmarshaller { public static final XmlUnmarshaller<String> STRING = new SimpleTypePayloadUnmarshaller<>(StringToValueConverter.TO_STRING); public static final XmlUnmarshaller<Integer> INTEGER = new SimpleTypePayloadUnmarshaller<>(StringToValueConverter.TO_INTEGER); public static final XmlUnmarshaller<Long> LONG = new SimpleTypePayloadUnmarshaller<>(StringToValueConverter.TO_LONG); public static final XmlUnmarshaller<Short> SHORT = new SimpleTypePayloadUnmarshaller<>(StringToValueConverter.TO_SHORT); public static final XmlUnmarshaller<Float> FLOAT = new SimpleTypePayloadUnmarshaller<>(StringToValueConverter.TO_FLOAT); public static final XmlUnmarshaller<Double> DOUBLE = new SimpleTypePayloadUnmarshaller<>(StringToValueConverter.TO_DOUBLE); public static final XmlUnmarshaller<BigDecimal> BIG_DECIMAL = new SimpleTypePayloadUnmarshaller<>(StringToValueConverter.TO_BIG_DECIMAL); public static final XmlUnmarshaller<Boolean> BOOLEAN = new SimpleTypePayloadUnmarshaller<>(StringToValueConverter.TO_BOOLEAN); public static final XmlUnmarshaller<Instant> INSTANT = new SimpleTypePayloadUnmarshaller<>(XmlProtocolUnmarshaller.INSTANT_STRING_TO_VALUE); public static final XmlUnmarshaller<SdkBytes> SDK_BYTES = new SimpleTypePayloadUnmarshaller<>(StringToValueConverter.TO_SDK_BYTES); private XmlPayloadUnmarshaller() { } public static SdkPojo unmarshallSdkPojo(XmlUnmarshallerContext context, List<XmlElement> content, SdkField<SdkPojo> field) { return context.protocolUnmarshaller() .unmarshall(context, field.constructor().get(), content.get(0)); } public static List<?> unmarshallList(XmlUnmarshallerContext context, List<XmlElement> content, SdkField<List<?>> field) { ListTrait listTrait = field.getTrait(ListTrait.class); List<Object> list = new ArrayList<>(); getMembers(content, listTrait).forEach(member -> { XmlUnmarshaller unmarshaller = context.getUnmarshaller(listTrait.memberFieldInfo().location(), listTrait.memberFieldInfo().marshallingType()); list.add(unmarshaller.unmarshall(context, singletonList(member), listTrait.memberFieldInfo())); }); return list; } private static List<XmlElement> getMembers(List<XmlElement> content, ListTrait listTrait) { String memberLocation = listTrait.memberLocationName() != null ? listTrait.memberLocationName() : listTrait.memberFieldInfo().locationName(); return listTrait.isFlattened() ? content : content.get(0).getElementsByName(memberLocation); } public static Map<String, ?> unmarshallMap(XmlUnmarshallerContext context, List<XmlElement> content, SdkField<Map<String, ?>> field) { Map<String, Object> map = new HashMap<>(); MapTrait mapTrait = field.getTrait(MapTrait.class); SdkField mapValueSdkField = mapTrait.valueFieldInfo(); getEntries(content, mapTrait).forEach(entry -> { XmlElement key = entry.getElementByName(mapTrait.keyLocationName()); XmlElement value = entry.getElementByName(mapTrait.valueLocationName()); XmlUnmarshaller unmarshaller = context.getUnmarshaller(mapValueSdkField.location(), mapValueSdkField.marshallingType()); map.put(key.textContent(), unmarshaller.unmarshall(context, singletonList(value), mapValueSdkField)); }); return map; } private static List<XmlElement> getEntries(List<XmlElement> content, MapTrait mapTrait) { return mapTrait.isFlattened() ? content : content.get(0).getElementsByName("entry"); } /** * Base payload unmarshaller for simple types of xml protocol * @param <T> Type to unmarshall */ private static class SimpleTypePayloadUnmarshaller<T> implements XmlUnmarshaller<T> { private final StringToValueConverter.StringToValue<T> converter; private SimpleTypePayloadUnmarshaller(StringToValueConverter.StringToValue<T> converter) { this.converter = converter; } @Override public T unmarshall(XmlUnmarshallerContext context, List<XmlElement> content, SdkField<T> field) { if (content == null) { return null; } return converter.convert(content.get(0).textContent(), field); } } }
2,526
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/unmarshall/XmlResponseParserUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.xml.internal.unmarshall; import java.io.IOException; import java.io.UncheckedIOException; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.protocol.MarshallLocation; import software.amazon.awssdk.core.protocol.MarshallingType; import software.amazon.awssdk.core.traits.PayloadTrait; import software.amazon.awssdk.http.AbortableInputStream; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.protocols.query.unmarshall.XmlDomParser; import software.amazon.awssdk.protocols.query.unmarshall.XmlElement; import software.amazon.awssdk.utils.LookaheadInputStream; /** * Static methods to assist with parsing the response of AWS XML requests. */ @SdkInternalApi public final class XmlResponseParserUtils { private XmlResponseParserUtils() { } /** * Parse an XML response if one is expected and available. If we are not expecting a payload, but the HTTP response * code shows an error then we will parse it anyway, as it should contain a serialized error. * @param sdkPojo the SDK builder object associated with the final response * @param response the HTTP response * @return A parsed XML document or an empty XML document if no payload/contents were found in the response. */ public static XmlElement parse(SdkPojo sdkPojo, SdkHttpFullResponse response) { try { Optional<AbortableInputStream> responseContent = response.content(); if (!responseContent.isPresent() || (response.isSuccessful() && !hasPayloadMembers(sdkPojo)) || getBlobTypePayloadMemberToUnmarshal(sdkPojo).isPresent()) { return XmlElement.empty(); } // Make sure there is content in the stream before passing it to the parser. LookaheadInputStream content = new LookaheadInputStream(responseContent.get()); if (content.peek() == -1) { return XmlElement.empty(); } return XmlDomParser.parse(content); } catch (IOException e) { throw new UncheckedIOException(e); } catch (RuntimeException e) { if (response.isSuccessful()) { throw e; } return XmlElement.empty(); } } /** * Gets the Member which is a Payload and which is of Blob Type. * @param sdkPojo * @return Optional of SdkField member if member is Blob type payload else returns Empty. */ public static Optional<SdkField<?>> getBlobTypePayloadMemberToUnmarshal(SdkPojo sdkPojo) { return sdkPojo.sdkFields().stream() .filter(e -> isExplicitPayloadMember(e)) .filter(f -> f.marshallingType() == MarshallingType.SDK_BYTES).findFirst(); } private static boolean isExplicitPayloadMember(SdkField<?> f) { return f.containsTrait(PayloadTrait.class); } private static boolean hasPayloadMembers(SdkPojo sdkPojo) { return sdkPojo.sdkFields().stream() .anyMatch(f -> f.location() == MarshallLocation.PAYLOAD); } }
2,527
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/unmarshall/XmlProtocolUnmarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.xml.internal.unmarshall; import static java.util.Collections.singletonList; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.time.Instant; import java.util.Collections; import java.util.EnumMap; import java.util.List; import java.util.Map; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.protocol.MarshallLocation; import software.amazon.awssdk.core.protocol.MarshallingType; import software.amazon.awssdk.core.traits.PayloadTrait; import software.amazon.awssdk.core.traits.TimestampFormatTrait; import software.amazon.awssdk.core.traits.XmlAttributeTrait; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.protocols.core.StringToInstant; import software.amazon.awssdk.protocols.core.StringToValueConverter; import software.amazon.awssdk.protocols.query.unmarshall.XmlDomParser; import software.amazon.awssdk.protocols.query.unmarshall.XmlElement; import software.amazon.awssdk.protocols.query.unmarshall.XmlErrorUnmarshaller; import software.amazon.awssdk.utils.CollectionUtils; import software.amazon.awssdk.utils.builder.Buildable; @SdkInternalApi public final class XmlProtocolUnmarshaller implements XmlErrorUnmarshaller { public static final StringToValueConverter.StringToValue<Instant> INSTANT_STRING_TO_VALUE = StringToInstant.create(getDefaultTimestampFormats()); private static final XmlUnmarshallerRegistry REGISTRY = createUnmarshallerRegistry(); private XmlProtocolUnmarshaller() { } public static XmlProtocolUnmarshaller create() { return new XmlProtocolUnmarshaller(); } public <TypeT extends SdkPojo> TypeT unmarshall(SdkPojo sdkPojo, SdkHttpFullResponse response) { XmlElement document = hasXmlPayload(sdkPojo, response) ? XmlResponseParserUtils.parse(sdkPojo, response) : null; return unmarshall(sdkPojo, document, response); } /** * This method is also used to unmarshall exceptions. We use this since we've already parsed the XML * and the result root is in a different location depending on the protocol/service. */ @Override public <TypeT extends SdkPojo> TypeT unmarshall(SdkPojo sdkPojo, XmlElement resultRoot, SdkHttpFullResponse response) { XmlUnmarshallerContext unmarshallerContext = XmlUnmarshallerContext.builder() .response(response) .registry(REGISTRY) .protocolUnmarshaller(this) .build(); return (TypeT) unmarshall(unmarshallerContext, sdkPojo, resultRoot); } SdkPojo unmarshall(XmlUnmarshallerContext context, SdkPojo sdkPojo, XmlElement root) { for (SdkField<?> field : sdkPojo.sdkFields()) { XmlUnmarshaller<Object> unmarshaller = REGISTRY.getUnmarshaller(field.location(), field.marshallingType()); if (field.location() != MarshallLocation.PAYLOAD) { Object unmarshalled = unmarshaller.unmarshall(context, null, (SdkField<Object>) field); field.set(sdkPojo, unmarshalled); continue; } if (isExplicitPayloadMember(field)) { InputStream content = context.response().content().orElse(null); if (field.marshallingType() == MarshallingType.SDK_BYTES) { SdkBytes value = content == null ? SdkBytes.fromByteArrayUnsafe(new byte[0]) : SdkBytes.fromInputStream(content); field.set(sdkPojo, value); continue; } if (field.marshallingType() == MarshallingType.STRING) { // TODO: If we ever break protected APIs, just parse this as a string and remove XML-wrapping // compatibility for S3. if (content == null) { field.set(sdkPojo, ""); } else { setExplicitStringPayload(unmarshaller, context, sdkPojo, root, field); } continue; } if (root != null && !isAttribute(field)) { Object unmarshalled = unmarshaller.unmarshall(context, singletonList(root), (SdkField<Object>) field); field.set(sdkPojo, unmarshalled); continue; } } if (root == null) { continue; } if (isAttribute(field)) { root.getOptionalAttributeByName(field.unmarshallLocationName()) .ifPresent(e -> field.set(sdkPojo, e)); continue; } List<XmlElement> element = root.getElementsByName(field.unmarshallLocationName()); if (!CollectionUtils.isNullOrEmpty(element)) { Object unmarshalled = unmarshaller.unmarshall(context, element, (SdkField<Object>) field); field.set(sdkPojo, unmarshalled); } } if (!(sdkPojo instanceof Buildable)) { throw new RuntimeException("The sdkPojo passed to the unmarshaller is not buildable (must implement " + "Buildable)"); } return (SdkPojo) ((Buildable) sdkPojo).build(); } private void setExplicitStringPayload(XmlUnmarshaller<Object> unmarshaller, XmlUnmarshallerContext context, SdkPojo sdkPojo, XmlElement element, SdkField<?> field) { SdkBytes sdkBytes = SdkBytes.fromInputStream(context.response().content().get()); String stringPayload = sdkBytes.asUtf8String(); if (hasS3XmlEnvelopePrefix(stringPayload)) { InputStream inputStream = new ByteArrayInputStream(sdkBytes.asByteArray()); XmlElement document = XmlDomParser.parse(inputStream); Object unmarshalled = unmarshaller.unmarshall(context, singletonList(document), (SdkField<Object>) field); field.set(sdkPojo, unmarshalled); } else { if (stringPayload.isEmpty()) { if (element == null) { // User passed in empty String field.set(sdkPojo, ""); } else { // InputStream may have already been read Object unmarshalled = unmarshaller.unmarshall(context, singletonList(element), (SdkField<Object>) field); field.set(sdkPojo, unmarshalled); } } else { field.set(sdkPojo, stringPayload); } } } // Handle S3 GetBucketPolicy(), which returns JSON so we wrap with XML private boolean hasS3XmlEnvelopePrefix(String payload) { String s3XmlEnvelopePrefix = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Policy><![CDATA["; return payload.startsWith(s3XmlEnvelopePrefix); } private boolean isAttribute(SdkField<?> field) { return field.containsTrait(XmlAttributeTrait.class); } private boolean isExplicitPayloadMember(SdkField<?> field) { return field.containsTrait(PayloadTrait.class); } private boolean hasXmlPayload(SdkPojo sdkPojo, SdkHttpFullResponse response) { return sdkPojo.sdkFields() .stream() .anyMatch(f -> isPayloadMemberOnUnmarshall(f) && !isExplicitBlobPayloadMember(f) && !isExplicitStringPayloadMember(f)) && response.content().isPresent(); } private boolean isExplicitBlobPayloadMember(SdkField<?> f) { return isExplicitPayloadMember(f) && f.marshallingType() == MarshallingType.SDK_BYTES; } private boolean isExplicitStringPayloadMember(SdkField<?> f) { return isExplicitPayloadMember(f) && f.marshallingType() == MarshallingType.STRING; } private boolean isPayloadMemberOnUnmarshall(SdkField<?> f) { return f.location() == MarshallLocation.PAYLOAD || isInUri(f.location()); } private static boolean isInUri(MarshallLocation location) { switch (location) { case PATH: case QUERY_PARAM: return true; default: return false; } } private static Map<MarshallLocation, TimestampFormatTrait.Format> getDefaultTimestampFormats() { Map<MarshallLocation, TimestampFormatTrait.Format> formats = new EnumMap<>(MarshallLocation.class); formats.put(MarshallLocation.HEADER, TimestampFormatTrait.Format.RFC_822); formats.put(MarshallLocation.PAYLOAD, TimestampFormatTrait.Format.ISO_8601); return Collections.unmodifiableMap(formats); } private static XmlUnmarshallerRegistry createUnmarshallerRegistry() { return XmlUnmarshallerRegistry .builder() .statusCodeUnmarshaller(MarshallingType.INTEGER, (context, content, field) -> context.response().statusCode()) .headerUnmarshaller(MarshallingType.STRING, HeaderUnmarshaller.STRING) .headerUnmarshaller(MarshallingType.INTEGER, HeaderUnmarshaller.INTEGER) .headerUnmarshaller(MarshallingType.LONG, HeaderUnmarshaller.LONG) .headerUnmarshaller(MarshallingType.SHORT, HeaderUnmarshaller.SHORT) .headerUnmarshaller(MarshallingType.DOUBLE, HeaderUnmarshaller.DOUBLE) .headerUnmarshaller(MarshallingType.BOOLEAN, HeaderUnmarshaller.BOOLEAN) .headerUnmarshaller(MarshallingType.INSTANT, HeaderUnmarshaller.INSTANT) .headerUnmarshaller(MarshallingType.FLOAT, HeaderUnmarshaller.FLOAT) .headerUnmarshaller(MarshallingType.MAP, HeaderUnmarshaller.MAP) .headerUnmarshaller(MarshallingType.LIST, HeaderUnmarshaller.LIST) .payloadUnmarshaller(MarshallingType.STRING, XmlPayloadUnmarshaller.STRING) .payloadUnmarshaller(MarshallingType.INTEGER, XmlPayloadUnmarshaller.INTEGER) .payloadUnmarshaller(MarshallingType.LONG, XmlPayloadUnmarshaller.LONG) .payloadUnmarshaller(MarshallingType.SHORT, XmlPayloadUnmarshaller.SHORT) .payloadUnmarshaller(MarshallingType.FLOAT, XmlPayloadUnmarshaller.FLOAT) .payloadUnmarshaller(MarshallingType.DOUBLE, XmlPayloadUnmarshaller.DOUBLE) .payloadUnmarshaller(MarshallingType.BIG_DECIMAL, XmlPayloadUnmarshaller.BIG_DECIMAL) .payloadUnmarshaller(MarshallingType.BOOLEAN, XmlPayloadUnmarshaller.BOOLEAN) .payloadUnmarshaller(MarshallingType.INSTANT, XmlPayloadUnmarshaller.INSTANT) .payloadUnmarshaller(MarshallingType.SDK_BYTES, XmlPayloadUnmarshaller.SDK_BYTES) .payloadUnmarshaller(MarshallingType.SDK_POJO, XmlPayloadUnmarshaller::unmarshallSdkPojo) .payloadUnmarshaller(MarshallingType.LIST, XmlPayloadUnmarshaller::unmarshallList) .payloadUnmarshaller(MarshallingType.MAP, XmlPayloadUnmarshaller::unmarshallMap) .build(); } }
2,528
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/unmarshall/AwsXmlUnmarshallingContext.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.xml.internal.unmarshall; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.protocols.query.unmarshall.XmlElement; /** * A data class to hold all the context of an unmarshalling stage for the AWS XML protocol as orchestrated by * {@link AwsXmlPredicatedResponseHandler}. */ @SdkInternalApi public class AwsXmlUnmarshallingContext { private final SdkHttpFullResponse sdkHttpFullResponse; private final XmlElement parsedXml; private final ExecutionAttributes executionAttributes; private final Boolean isResponseSuccess; private final XmlElement parsedErrorXml; private AwsXmlUnmarshallingContext(Builder builder) { this.sdkHttpFullResponse = builder.sdkHttpFullResponse; this.parsedXml = builder.parsedXml; this.executionAttributes = builder.executionAttributes; this.isResponseSuccess = builder.isResponseSuccess; this.parsedErrorXml = builder.parsedErrorXml; } public static Builder builder() { return new Builder(); } /** * The HTTP response. */ public SdkHttpFullResponse sdkHttpFullResponse() { return sdkHttpFullResponse; } /** * The parsed XML of the body, or null if there was no body. */ public XmlElement parsedRootXml() { return parsedXml; } /** * The {@link ExecutionAttributes} associated with this request. */ public ExecutionAttributes executionAttributes() { return executionAttributes; } /** * true if the response indicates success; false if not; null if that has not been determined yet */ public Boolean isResponseSuccess() { return isResponseSuccess; } /** * The parsed XML of just the error. null if not found or determined yet. */ public XmlElement parsedErrorXml() { return parsedErrorXml; } public Builder toBuilder() { return builder().sdkHttpFullResponse(this.sdkHttpFullResponse) .parsedXml(this.parsedXml) .executionAttributes(this.executionAttributes) .isResponseSuccess(this.isResponseSuccess) .parsedErrorXml(this.parsedErrorXml); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AwsXmlUnmarshallingContext that = (AwsXmlUnmarshallingContext) o; if (sdkHttpFullResponse != null ? ! sdkHttpFullResponse.equals(that.sdkHttpFullResponse) : that.sdkHttpFullResponse != null) { return false; } if (parsedXml != null ? ! parsedXml.equals(that.parsedXml) : that.parsedXml != null) { return false; } if (executionAttributes != null ? ! executionAttributes.equals(that.executionAttributes) : that.executionAttributes != null) { return false; } if (isResponseSuccess != null ? ! isResponseSuccess.equals(that.isResponseSuccess) : that.isResponseSuccess != null) { return false; } return parsedErrorXml != null ? parsedErrorXml.equals(that.parsedErrorXml) : that.parsedErrorXml == null; } @Override public int hashCode() { int result = sdkHttpFullResponse != null ? sdkHttpFullResponse.hashCode() : 0; result = 31 * result + (parsedXml != null ? parsedXml.hashCode() : 0); result = 31 * result + (executionAttributes != null ? executionAttributes.hashCode() : 0); result = 31 * result + (isResponseSuccess != null ? isResponseSuccess.hashCode() : 0); result = 31 * result + (parsedErrorXml != null ? parsedErrorXml.hashCode() : 0); return result; } public static final class Builder { private SdkHttpFullResponse sdkHttpFullResponse; private XmlElement parsedXml; private ExecutionAttributes executionAttributes; private Boolean isResponseSuccess; private XmlElement parsedErrorXml; private Builder() { } public Builder sdkHttpFullResponse(SdkHttpFullResponse sdkHttpFullResponse) { this.sdkHttpFullResponse = sdkHttpFullResponse; return this; } public Builder parsedXml(XmlElement parsedXml) { this.parsedXml = parsedXml; return this; } public Builder executionAttributes(ExecutionAttributes executionAttributes) { this.executionAttributes = executionAttributes; return this; } public Builder isResponseSuccess(Boolean isResponseSuccess) { this.isResponseSuccess = isResponseSuccess; return this; } public Builder parsedErrorXml(XmlElement parsedErrorXml) { this.parsedErrorXml = parsedErrorXml; return this; } public AwsXmlUnmarshallingContext build() { return new AwsXmlUnmarshallingContext(this); } } }
2,529
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/unmarshall/XmlUnmarshallerContext.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.xml.internal.unmarshall; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.protocol.MarshallLocation; import software.amazon.awssdk.core.protocol.MarshallingType; import software.amazon.awssdk.http.SdkHttpFullResponse; @SdkInternalApi public final class XmlUnmarshallerContext { private final SdkHttpFullResponse response; private final XmlUnmarshallerRegistry registry; private final XmlProtocolUnmarshaller protocolUnmarshaller; private XmlUnmarshallerContext(Builder builder) { this.response = builder.response; this.registry = builder.registry; this.protocolUnmarshaller = builder.protocolUnmarshaller; } /** * @return The {@link SdkHttpFullResponse} of the API call. */ public SdkHttpFullResponse response() { return response; } public XmlProtocolUnmarshaller protocolUnmarshaller() { return protocolUnmarshaller; } public <T> XmlUnmarshaller<Object> getUnmarshaller(MarshallLocation marshallLocation, MarshallingType<T> marshallingType) { return registry.getUnmarshaller(marshallLocation, marshallingType); } /** * @return Builder instance to construct a {@link XmlUnmarshallerContext}. */ public static Builder builder() { return new Builder(); } /** * Builder for a {@link XmlUnmarshallerContext}. */ public static final class Builder { private SdkHttpFullResponse response; private XmlUnmarshallerRegistry registry; private XmlProtocolUnmarshaller protocolUnmarshaller; private Builder() { } public Builder response(SdkHttpFullResponse response) { this.response = response; return this; } public Builder registry(XmlUnmarshallerRegistry registry) { this.registry = registry; return this; } public Builder protocolUnmarshaller(XmlProtocolUnmarshaller protocolUnmarshaller) { this.protocolUnmarshaller = protocolUnmarshaller; return this; } /** * @return An immutable {@link XmlUnmarshallerContext} object. */ public XmlUnmarshallerContext build() { return new XmlUnmarshallerContext(this); } } }
2,530
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/unmarshall/XmlResponseHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.xml.internal.unmarshall; import java.io.IOException; import java.util.function.Function; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.SdkStandardLogger; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.utils.Logger; /** * Response handler for REST-XML services (Cloudfront, Route53, and S3). * * @param <T> Indicates the type being unmarshalled by this response handler. */ @SdkInternalApi public final class XmlResponseHandler<T extends SdkPojo> implements HttpResponseHandler<T> { private static final Logger log = Logger.loggerFor(XmlResponseHandler.class); private final XmlProtocolUnmarshaller unmarshaller; private final Function<SdkHttpFullResponse, SdkPojo> pojoSupplier; private final boolean needsConnectionLeftOpen; public XmlResponseHandler(XmlProtocolUnmarshaller unmarshaller, Function<SdkHttpFullResponse, SdkPojo> pojoSupplier, boolean needsConnectionLeftOpen) { this.unmarshaller = unmarshaller; this.pojoSupplier = pojoSupplier; this.needsConnectionLeftOpen = needsConnectionLeftOpen; } @Override public T handle(SdkHttpFullResponse response, ExecutionAttributes executionAttributes) throws Exception { try { return unmarshallResponse(response); } finally { if (!needsConnectionLeftOpen) { closeStream(response); } } } private void closeStream(SdkHttpFullResponse response) { response.content().ifPresent(i -> { try { i.close(); } catch (IOException e) { log.warn(() -> "Error closing HTTP content.", e); } }); } @SuppressWarnings("unchecked") private T unmarshallResponse(SdkHttpFullResponse response) throws Exception { SdkStandardLogger.REQUEST_LOGGER.trace(() -> "Parsing service response XML."); T result = unmarshaller.unmarshall(pojoSupplier.apply(response), response); SdkStandardLogger.REQUEST_LOGGER.trace(() -> "Done parsing service response."); return result; } @Override public boolean needsConnectionLeftOpen() { return needsConnectionLeftOpen; } }
2,531
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/unmarshall/AwsXmlErrorTransformer.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.xml.internal.unmarshall; import java.util.List; import java.util.Optional; import java.util.function.Function; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.protocols.core.ExceptionMetadata; import software.amazon.awssdk.protocols.query.internal.unmarshall.AwsXmlErrorUnmarshaller; import software.amazon.awssdk.protocols.query.unmarshall.XmlErrorUnmarshaller; /** * A transformer function that takes a parsed XML response and converts it into an {@link AwsServiceException}. Used * as a component in the {@link AwsXmlPredicatedResponseHandler}. */ @SdkInternalApi public final class AwsXmlErrorTransformer implements Function<AwsXmlUnmarshallingContext, AwsServiceException> { private final AwsXmlErrorUnmarshaller awsXmlErrorUnmarshaller; private AwsXmlErrorTransformer(Builder builder) { this.awsXmlErrorUnmarshaller = AwsXmlErrorUnmarshaller.builder() .defaultExceptionSupplier(builder.defaultExceptionSupplier) .exceptions(builder.exceptions) .errorUnmarshaller(builder.errorUnmarshaller) .build(); } @Override public AwsServiceException apply(AwsXmlUnmarshallingContext context) { return awsXmlErrorUnmarshaller.unmarshall(context.parsedRootXml(), Optional.ofNullable(context.parsedErrorXml()), Optional.empty(), context.sdkHttpFullResponse(), context.executionAttributes()); } /** * @return New Builder instance. */ public static Builder builder() { return new Builder(); } /** * Builder for {@link AwsXmlErrorTransformer}. */ public static final class Builder { private List<ExceptionMetadata> exceptions; private Supplier<SdkPojo> defaultExceptionSupplier; private XmlErrorUnmarshaller errorUnmarshaller; private Builder() { } /** * List of {@link ExceptionMetadata} to represent the modeled exceptions for the service. * For AWS services the error type is a string representing the type of the modeled exception. * * @return This builder for method chaining. */ public Builder exceptions(List<ExceptionMetadata> exceptions) { this.exceptions = exceptions; return this; } /** * Default exception type if "error code" does not match any known modeled exception. This is the generated * base exception for the service (i.e. DynamoDbException). * * @return This builder for method chaining. */ public Builder defaultExceptionSupplier(Supplier<SdkPojo> defaultExceptionSupplier) { this.defaultExceptionSupplier = defaultExceptionSupplier; return this; } /** * The unmarshaller to use. The unmarshaller only unmarshalls any modeled fields of the exception, * additional metadata is extracted by {@link AwsXmlErrorTransformer}. * * @param errorUnmarshaller Error unmarshaller to use. * @return This builder for method chaining. */ public Builder errorUnmarshaller(XmlErrorUnmarshaller errorUnmarshaller) { this.errorUnmarshaller = errorUnmarshaller; return this; } /** * @return New instance of {@link AwsXmlErrorTransformer}. */ public AwsXmlErrorTransformer build() { return new AwsXmlErrorTransformer(this); } } }
2,532
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/marshall/XmlPayloadMarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.xml.internal.marshall; import java.math.BigDecimal; import java.time.Instant; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.protocol.MarshallLocation; import software.amazon.awssdk.core.traits.ListTrait; import software.amazon.awssdk.core.traits.MapTrait; import software.amazon.awssdk.core.traits.RequiredTrait; import software.amazon.awssdk.core.traits.XmlAttributeTrait; import software.amazon.awssdk.core.traits.XmlAttributesTrait; import software.amazon.awssdk.core.util.SdkAutoConstructList; import software.amazon.awssdk.core.util.SdkAutoConstructMap; import software.amazon.awssdk.protocols.core.ValueToStringConverter; @SdkInternalApi public class XmlPayloadMarshaller { public static final XmlMarshaller<String> STRING = new BasePayloadMarshaller<>(ValueToStringConverter.FROM_STRING); public static final XmlMarshaller<Integer> INTEGER = new BasePayloadMarshaller<>(ValueToStringConverter.FROM_INTEGER); public static final XmlMarshaller<Long> LONG = new BasePayloadMarshaller<>(ValueToStringConverter.FROM_LONG); public static final XmlMarshaller<Short> SHORT = new BasePayloadMarshaller<>(ValueToStringConverter.FROM_SHORT); public static final XmlMarshaller<Float> FLOAT = new BasePayloadMarshaller<>(ValueToStringConverter.FROM_FLOAT); public static final XmlMarshaller<Double> DOUBLE = new BasePayloadMarshaller<>(ValueToStringConverter.FROM_DOUBLE); public static final XmlMarshaller<BigDecimal> BIG_DECIMAL = new BasePayloadMarshaller<>(ValueToStringConverter.FROM_BIG_DECIMAL); public static final XmlMarshaller<Boolean> BOOLEAN = new BasePayloadMarshaller<>(ValueToStringConverter.FROM_BOOLEAN); public static final XmlMarshaller<Instant> INSTANT = new BasePayloadMarshaller<>(XmlProtocolMarshaller.INSTANT_VALUE_TO_STRING); public static final XmlMarshaller<SdkBytes> SDK_BYTES = new BasePayloadMarshaller<>(ValueToStringConverter.FROM_SDK_BYTES); public static final XmlMarshaller<SdkPojo> SDK_POJO = new BasePayloadMarshaller<SdkPojo>(null) { @Override public void marshall(SdkPojo val, XmlMarshallerContext context, String paramName, SdkField<SdkPojo> sdkField, ValueToStringConverter.ValueToString<SdkPojo> converter) { context.protocolMarshaller().doMarshall(val); } }; public static final XmlMarshaller<List<?>> LIST = new BasePayloadMarshaller<List<?>>(null) { @Override public void marshall(List<?> val, XmlMarshallerContext context, String paramName, SdkField<List<?>> sdkField) { if (!shouldEmit(val, paramName)) { return; } marshall(val, context, paramName, sdkField, null); } @Override public void marshall(List<?> list, XmlMarshallerContext context, String paramName, SdkField<List<?>> sdkField, ValueToStringConverter.ValueToString<List<?>> converter) { ListTrait listTrait = sdkField.getRequiredTrait(ListTrait.class); if (!listTrait.isFlattened()) { context.xmlGenerator().startElement(paramName); } SdkField memberField = listTrait.memberFieldInfo(); String memberLocationName = listMemberLocationName(listTrait, paramName); for (Object listMember : list) { context.marshall(MarshallLocation.PAYLOAD, listMember, memberLocationName, memberField); } if (!listTrait.isFlattened()) { context.xmlGenerator().endElement(); } } private String listMemberLocationName(ListTrait listTrait, String listLocationName) { String locationName = listTrait.memberLocationName(); if (locationName == null) { locationName = listTrait.isFlattened() ? listLocationName : "member"; } return locationName; } @Override protected boolean shouldEmit(List list, String paramName) { return super.shouldEmit(list, paramName) && (!list.isEmpty() || !(list instanceof SdkAutoConstructList)); } }; // We ignore flattened trait for maps. For rest-xml, none of the services have flattened maps public static final XmlMarshaller<Map<String, ?>> MAP = new BasePayloadMarshaller<Map<String, ?>>(null) { @Override public void marshall(Map<String, ?> map, XmlMarshallerContext context, String paramName, SdkField<Map<String, ?>> sdkField, ValueToStringConverter.ValueToString<Map<String, ?>> converter) { MapTrait mapTrait = sdkField.getRequiredTrait(MapTrait.class); for (Map.Entry<String, ?> entry : map.entrySet()) { context.xmlGenerator().startElement("entry"); context.marshall(MarshallLocation.PAYLOAD, entry.getKey(), mapTrait.keyLocationName(), null); context.marshall(MarshallLocation.PAYLOAD, entry.getValue(), mapTrait.valueLocationName(), mapTrait.valueFieldInfo()); context.xmlGenerator().endElement(); } } @Override protected boolean shouldEmit(Map map, String paramName) { return super.shouldEmit(map, paramName) && (!map.isEmpty() || !(map instanceof SdkAutoConstructMap)); } }; public static final XmlMarshaller<Void> NULL = (val, context, paramName, sdkField) -> { if (Objects.nonNull(sdkField) && sdkField.containsTrait(RequiredTrait.class)) { throw new IllegalArgumentException(String.format("Parameter '%s' must not be null", paramName)); } }; private XmlPayloadMarshaller() { } /** * Base payload marshaller for xml protocol. Marshalling happens only when both element name and value are present. * * Marshalling for simple types is done in the base class. * Complex types should override the * {@link #marshall(Object, XmlMarshallerContext, String, SdkField, ValueToStringConverter.ValueToString)} method. * * @param <T> Type to marshall */ private static class BasePayloadMarshaller<T> implements XmlMarshaller<T> { private final ValueToStringConverter.ValueToString<T> converter; private BasePayloadMarshaller(ValueToStringConverter.ValueToString<T> converter) { this.converter = converter; } @Override public void marshall(T val, XmlMarshallerContext context, String paramName, SdkField<T> sdkField) { if (!shouldEmit(val, paramName)) { return; } // Should ignore marshalling for xml attribute if (isXmlAttribute(sdkField)) { return; } if (sdkField != null && sdkField.getOptionalTrait(XmlAttributesTrait.class).isPresent()) { XmlAttributesTrait attributeTrait = sdkField.getTrait(XmlAttributesTrait.class); Map<String, String> attributes = attributeTrait.attributes() .entrySet() .stream() .collect(LinkedHashMap::new, (m, e) -> m.put(e.getKey(), e.getValue() .attributeGetter() .apply(val)), HashMap::putAll); context.xmlGenerator().startElement(paramName, attributes); } else { context.xmlGenerator().startElement(paramName); } marshall(val, context, paramName, sdkField, converter); context.xmlGenerator().endElement(); } void marshall(T val, XmlMarshallerContext context, String paramName, SdkField<T> sdkField, ValueToStringConverter.ValueToString<T> converter) { context.xmlGenerator().xmlWriter().value(converter.convert(val, sdkField)); } protected boolean shouldEmit(T val, String paramName) { return val != null && paramName != null; } private boolean isXmlAttribute(SdkField<T> sdkField) { return sdkField != null && sdkField.getOptionalTrait(XmlAttributeTrait.class).isPresent(); } } }
2,533
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/marshall/XmlMarshallerRegistry.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.xml.internal.marshall; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.protocol.MarshallLocation; import software.amazon.awssdk.core.protocol.MarshallingType; import software.amazon.awssdk.protocols.core.AbstractMarshallingRegistry; @SdkInternalApi public final class XmlMarshallerRegistry extends AbstractMarshallingRegistry { private XmlMarshallerRegistry(Builder builder) { super(builder); } @SuppressWarnings("unchecked") public <T> XmlMarshaller<T> getMarshaller(MarshallLocation marshallLocation, T val) { return (XmlMarshaller<T>) get(marshallLocation, toMarshallingType(val)); } @SuppressWarnings("unchecked") public <T> XmlMarshaller<Object> getMarshaller(MarshallLocation marshallLocation, MarshallingType<T> marshallingType, Object val) { return (XmlMarshaller<Object>) get(marshallLocation, val == null ? MarshallingType.NULL : marshallingType); } /** * @return Builder instance to construct a {@link XmlMarshallerRegistry}. */ public static Builder builder() { return new Builder(); } /** * Builder for a {@link XmlMarshallerRegistry}. */ public static final class Builder extends AbstractMarshallingRegistry.Builder { private Builder() { } public <T> Builder payloadMarshaller(MarshallingType<T> marshallingType, XmlMarshaller<T> marshaller) { register(MarshallLocation.PAYLOAD, marshallingType, marshaller); return this; } public <T> Builder headerMarshaller(MarshallingType<T> marshallingType, XmlMarshaller<T> marshaller) { register(MarshallLocation.HEADER, marshallingType, marshaller); return this; } public <T> Builder queryParamMarshaller(MarshallingType<T> marshallingType, XmlMarshaller<T> marshaller) { register(MarshallLocation.QUERY_PARAM, marshallingType, marshaller); return this; } public <T> Builder pathParamMarshaller(MarshallingType<T> marshallingType, XmlMarshaller<T> marshaller) { register(MarshallLocation.PATH, marshallingType, marshaller); return this; } public <T> Builder greedyPathParamMarshaller(MarshallingType<T> marshallingType, XmlMarshaller<T> marshaller) { register(MarshallLocation.GREEDY_PATH, marshallingType, marshaller); return this; } /** * @return An immutable {@link XmlMarshallerRegistry} object. */ public XmlMarshallerRegistry build() { return new XmlMarshallerRegistry(this); } } }
2,534
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/marshall/SimpleTypePathMarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.xml.internal.marshall; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.protocols.core.PathMarshaller; import software.amazon.awssdk.protocols.core.ValueToStringConverter; @SdkInternalApi public final class SimpleTypePathMarshaller { public static final XmlMarshaller<String> STRING = new SimplePathMarshaller<>(ValueToStringConverter.FROM_STRING, PathMarshaller.NON_GREEDY); public static final XmlMarshaller<Integer> INTEGER = new SimplePathMarshaller<>(ValueToStringConverter.FROM_INTEGER, PathMarshaller.NON_GREEDY); public static final XmlMarshaller<Long> LONG = new SimplePathMarshaller<>(ValueToStringConverter.FROM_LONG, PathMarshaller.NON_GREEDY); public static final XmlMarshaller<Short> SHORT = new SimplePathMarshaller<>(ValueToStringConverter.FROM_SHORT, PathMarshaller.NON_GREEDY); /** * Marshallers for Strings bound to a greedy path param. No URL encoding is done on the string * so that it preserves the path structure. */ public static final XmlMarshaller<String> GREEDY_STRING = new SimplePathMarshaller<>(ValueToStringConverter.FROM_STRING, PathMarshaller.GREEDY_WITH_SLASHES); public static final XmlMarshaller<Void> NULL = (val, context, paramName, sdkField) -> { throw new IllegalArgumentException(String.format("Parameter '%s' must not be null", paramName)); }; private SimpleTypePathMarshaller() { } private static class SimplePathMarshaller<T> implements XmlMarshaller<T> { private final ValueToStringConverter.ValueToString<T> converter; private final PathMarshaller pathMarshaller; private SimplePathMarshaller(ValueToStringConverter.ValueToString<T> converter, PathMarshaller pathMarshaller) { this.converter = converter; this.pathMarshaller = pathMarshaller; } @Override public void marshall(T val, XmlMarshallerContext context, String paramName, SdkField<T> sdkField) { context.request().encodedPath( pathMarshaller.marshall(context.request().encodedPath(), paramName, converter.convert(val, sdkField))); } } }
2,535
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/marshall/HeaderMarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.xml.internal.marshall; import static software.amazon.awssdk.utils.CollectionUtils.isNullOrEmpty; import java.time.Instant; import java.util.List; import java.util.Map; import java.util.Objects; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.protocol.MarshallLocation; import software.amazon.awssdk.core.traits.ListTrait; import software.amazon.awssdk.core.traits.RequiredTrait; import software.amazon.awssdk.protocols.core.ValueToStringConverter; import software.amazon.awssdk.utils.StringUtils; @SdkInternalApi public final class HeaderMarshaller { public static final XmlMarshaller<String> STRING = new SimpleHeaderMarshaller<>(ValueToStringConverter.FROM_STRING); public static final XmlMarshaller<Integer> INTEGER = new SimpleHeaderMarshaller<>(ValueToStringConverter.FROM_INTEGER); public static final XmlMarshaller<Long> LONG = new SimpleHeaderMarshaller<>(ValueToStringConverter.FROM_LONG); public static final XmlMarshaller<Short> SHORT = new SimpleHeaderMarshaller<>(ValueToStringConverter.FROM_SHORT); public static final XmlMarshaller<Double> DOUBLE = new SimpleHeaderMarshaller<>(ValueToStringConverter.FROM_DOUBLE); public static final XmlMarshaller<Float> FLOAT = new SimpleHeaderMarshaller<>(ValueToStringConverter.FROM_FLOAT); public static final XmlMarshaller<Boolean> BOOLEAN = new SimpleHeaderMarshaller<>(ValueToStringConverter.FROM_BOOLEAN); public static final XmlMarshaller<Instant> INSTANT = new SimpleHeaderMarshaller<>(XmlProtocolMarshaller.INSTANT_VALUE_TO_STRING); public static final XmlMarshaller<Map<String, ?>> MAP = new SimpleHeaderMarshaller<Map<String, ?>>(null) { @Override public void marshall(Map<String, ?> map, XmlMarshallerContext context, String paramName, SdkField<Map<String, ?>> sdkField) { if (!shouldEmit(map)) { return; } for (Map.Entry<String, ?> entry : map.entrySet()) { String key = entry.getKey().startsWith(paramName) ? entry.getKey() : paramName + entry.getKey(); XmlMarshaller marshaller = context.marshallerRegistry().getMarshaller(MarshallLocation.HEADER, entry.getValue()); marshaller.marshall(entry.getValue(), context, key, null); } } @Override protected boolean shouldEmit(Map map) { return !isNullOrEmpty(map); } }; public static final XmlMarshaller<List<?>> LIST = new SimpleHeaderMarshaller<List<?>>(null) { @Override public void marshall(List<?> list, XmlMarshallerContext context, String paramName, SdkField<List<?>> sdkField) { if (!shouldEmit(list)) { return; } SdkField memberFieldInfo = sdkField.getRequiredTrait(ListTrait.class).memberFieldInfo(); for (Object listValue : list) { if (shouldSkipElement(listValue)) { continue; } XmlMarshaller marshaller = context.marshallerRegistry().getMarshaller(MarshallLocation.HEADER, listValue); marshaller.marshall(listValue, context, paramName, memberFieldInfo); } } private boolean shouldSkipElement(Object element) { return element instanceof String && StringUtils.isBlank((String) element); } @Override protected boolean shouldEmit(List list) { // Null or empty lists cannot be meaningfully (or safely) represented in an HTTP header message since header-fields // must typically have a non-empty field-value. https://datatracker.ietf.org/doc/html/rfc7230#section-3.2 return !isNullOrEmpty(list); } }; public static final XmlMarshaller<Void> NULL = (val, context, paramName, sdkField) -> { if (Objects.nonNull(sdkField) && sdkField.containsTrait(RequiredTrait.class)) { throw new IllegalArgumentException(String.format("Parameter '%s' must not be null", paramName)); } }; private HeaderMarshaller() { } private static class SimpleHeaderMarshaller<T> implements XmlMarshaller<T> { private final ValueToStringConverter.ValueToString<T> converter; private SimpleHeaderMarshaller(ValueToStringConverter.ValueToString<T> converter) { this.converter = converter; } @Override public void marshall(T val, XmlMarshallerContext context, String paramName, SdkField<T> sdkField) { if (!shouldEmit(val)) { return; } context.request().appendHeader(paramName, converter.convert(val, sdkField)); } protected boolean shouldEmit(T val) { return val != null; } } }
2,536
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/marshall/XmlGenerator.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.xml.internal.marshall; import java.io.StringWriter; import java.util.Map; import software.amazon.awssdk.annotations.SdkInternalApi; /** * Wrapper around the {@link XmlWriter} for marshalling requests for XML protocol */ @SdkInternalApi public final class XmlGenerator { private final StringWriter stringWriter; private final XmlWriter xmlWriter; private XmlGenerator(StringWriter stringWriter, XmlWriter xmlWriter) { this.stringWriter = stringWriter; this.xmlWriter = xmlWriter; } public static XmlGenerator create(String xmlns) { StringWriter stringWriter = new StringWriter(); return new XmlGenerator(stringWriter, new XmlWriter(stringWriter, xmlns)); } public XmlWriter xmlWriter() { return xmlWriter; } public StringWriter stringWriter() { return stringWriter; } public void startElement(String element) { xmlWriter.startElement(element); } /** * Start to write the element * * @param element the element to write * @param attributes the attributes */ public void startElement(String element, Map<String, String> attributes) { xmlWriter.startElement(element, attributes); } public void endElement() { xmlWriter.endElement(); } }
2,537
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/marshall/XmlMarshallerContext.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.xml.internal.marshall; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.protocol.MarshallLocation; import software.amazon.awssdk.http.SdkHttpFullRequest; @SdkInternalApi public final class XmlMarshallerContext { private final XmlGenerator xmlGenerator; private final XmlProtocolMarshaller protocolMarshaller; private final XmlMarshallerRegistry marshallerRegistry; private final SdkHttpFullRequest.Builder request; public XmlMarshallerContext(Builder builder) { this.xmlGenerator = builder.xmlGenerator; this.protocolMarshaller = builder.protocolMarshaller; this.marshallerRegistry = builder.marshallerRegistry; this.request = builder.request; } public XmlGenerator xmlGenerator() { return xmlGenerator; } public XmlProtocolMarshaller protocolMarshaller() { return protocolMarshaller; } /** * @return Marshaller registry to obtain marshaller implementations for nested types (i.e. lists of objects or maps of string * to string). */ public XmlMarshallerRegistry marshallerRegistry() { return marshallerRegistry; } /** * @return Mutable {@link SdkHttpFullRequest.Builder} object that can be used to add headers, query params, * modify request URI, etc. */ public SdkHttpFullRequest.Builder request() { return request; } /** * Convenience method to marshall a nested object (may be simple or structured) at the given location. * * @param marshallLocation Current {@link MarshallLocation} * @param val Value to marshall. */ public void marshall(MarshallLocation marshallLocation, Object val) { marshallerRegistry.getMarshaller(marshallLocation, val).marshall(val, this, null, null); } /** * Convenience method to marshall a nested object (may be simple or structured) at the given location. * * @param marshallLocation Current {@link MarshallLocation} * @param val Value to marshall. * @param paramName Name of parameter to marshall. * @param sdkField {@link SdkField} containing metadata about the member being marshalled. */ public <T> void marshall(MarshallLocation marshallLocation, T val, String paramName, SdkField<T> sdkField) { marshallerRegistry.getMarshaller(marshallLocation, val).marshall(val, this, paramName, sdkField); } /** * @return Builder instance to construct a {@link XmlMarshallerContext}. */ public static Builder builder() { return new Builder(); } /** * Builder for a {@link XmlMarshallerContext}. */ public static final class Builder { private XmlGenerator xmlGenerator; private XmlProtocolMarshaller protocolMarshaller; private XmlMarshallerRegistry marshallerRegistry; private SdkHttpFullRequest.Builder request; private Builder() { } public Builder xmlGenerator(XmlGenerator xmlGenerator) { this.xmlGenerator = xmlGenerator; return this; } public Builder protocolMarshaller(XmlProtocolMarshaller protocolMarshaller) { this.protocolMarshaller = protocolMarshaller; return this; } public Builder marshallerRegistry(XmlMarshallerRegistry marshallerRegistry) { this.marshallerRegistry = marshallerRegistry; return this; } public Builder request(SdkHttpFullRequest.Builder request) { this.request = request; return this; } public XmlMarshallerContext build() { return new XmlMarshallerContext(this); } } }
2,538
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/marshall/XmlProtocolMarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.xml.internal.marshall; import static software.amazon.awssdk.http.Header.CONTENT_LENGTH; import static software.amazon.awssdk.http.Header.CONTENT_TYPE; import java.io.ByteArrayInputStream; import java.net.URI; import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.Collections; import java.util.EnumMap; import java.util.Map; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.protocol.MarshallLocation; import software.amazon.awssdk.core.protocol.MarshallingType; import software.amazon.awssdk.core.traits.PayloadTrait; import software.amazon.awssdk.core.traits.TimestampFormatTrait; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.protocols.core.InstantToString; import software.amazon.awssdk.protocols.core.OperationInfo; import software.amazon.awssdk.protocols.core.ProtocolMarshaller; import software.amazon.awssdk.protocols.core.ProtocolUtils; import software.amazon.awssdk.protocols.core.ValueToStringConverter; import software.amazon.awssdk.protocols.xml.AwsXmlProtocolFactory; import software.amazon.awssdk.utils.StringInputStream; /** * Implementation of {@link ProtocolMarshaller} for REST-XML services. This is currently only Cloudfront, Route53, * and S3. */ @SdkInternalApi public final class XmlProtocolMarshaller implements ProtocolMarshaller<SdkHttpFullRequest> { public static final ValueToStringConverter.ValueToString<Instant> INSTANT_VALUE_TO_STRING = InstantToString.create(getDefaultTimestampFormats()); private static final XmlMarshallerRegistry MARSHALLER_REGISTRY = createMarshallerRegistry(); private final URI endpoint; private final SdkHttpFullRequest.Builder request; private final String rootElement; private final XmlMarshallerContext marshallerContext; private XmlProtocolMarshaller(Builder builder) { this.endpoint = builder.endpoint; this.request = ProtocolUtils.createSdkHttpRequest(builder.operationInfo, this.endpoint); this.rootElement = builder.operationInfo.addtionalMetadata(AwsXmlProtocolFactory.ROOT_MARSHALL_LOCATION_ATTRIBUTE); this.marshallerContext = XmlMarshallerContext.builder() .xmlGenerator(builder.xmlGenerator) .marshallerRegistry(MARSHALLER_REGISTRY) .protocolMarshaller(this) .request(request) .build(); } @Override public SdkHttpFullRequest marshall(SdkPojo pojo) { if (rootElement != null) { marshallerContext.xmlGenerator().startElement(rootElement); } doMarshall(pojo); if (rootElement != null) { marshallerContext.xmlGenerator().endElement(); } return finishMarshalling(pojo); } void doMarshall(SdkPojo pojo) { for (SdkField<?> field : pojo.sdkFields()) { Object val = field.getValueOrDefault(pojo); if (isBinary(field, val)) { request.contentStreamProvider(((SdkBytes) val)::asInputStream); setContentTypeHeaderIfNeeded("binary/octet-stream"); } else if (isExplicitPayloadMember(field) && val instanceof String) { byte[] content = ((String) val).getBytes(StandardCharsets.UTF_8); request.contentStreamProvider(() -> new ByteArrayInputStream(content)); request.putHeader(CONTENT_LENGTH, Integer.toString(content.length)); } else { MARSHALLER_REGISTRY.getMarshaller(field.location(), field.marshallingType(), val) .marshall(val, marshallerContext, field.locationName(), (SdkField<Object>) field); } } } private SdkHttpFullRequest finishMarshalling(SdkPojo pojo) { // Content may already be set if the payload is binary data. if (hasPayloadMembers(pojo) && request.contentStreamProvider() == null && marshallerContext.xmlGenerator() != null) { String content = marshallerContext.xmlGenerator().stringWriter().getBuffer().toString(); if (!content.isEmpty()) { request.contentStreamProvider(() -> new StringInputStream(content)); request.putHeader("Content-Length", Integer.toString(content.getBytes(StandardCharsets.UTF_8).length)); setContentTypeHeaderIfNeeded("application/xml"); } } return request.build(); } private boolean isBinary(SdkField<?> field, Object val) { return isExplicitPayloadMember(field) && val instanceof SdkBytes; } private boolean isExplicitPayloadMember(SdkField<?> field) { return field.containsTrait(PayloadTrait.class); } private boolean hasPayloadMembers(SdkPojo sdkPojo) { return sdkPojo.sdkFields().stream() .anyMatch(f -> f.location() == MarshallLocation.PAYLOAD); } private void setContentTypeHeaderIfNeeded(String contentType) { if (contentType != null && !request.firstMatchingHeader(CONTENT_TYPE).isPresent()) { request.putHeader(CONTENT_TYPE, contentType); } } private static Map<MarshallLocation, TimestampFormatTrait.Format> getDefaultTimestampFormats() { Map<MarshallLocation, TimestampFormatTrait.Format> formats = new EnumMap<>(MarshallLocation.class); formats.put(MarshallLocation.HEADER, TimestampFormatTrait.Format.RFC_822); formats.put(MarshallLocation.PAYLOAD, TimestampFormatTrait.Format.ISO_8601); formats.put(MarshallLocation.QUERY_PARAM, TimestampFormatTrait.Format.ISO_8601); return Collections.unmodifiableMap(formats); } private static XmlMarshallerRegistry createMarshallerRegistry() { return XmlMarshallerRegistry .builder() .payloadMarshaller(MarshallingType.STRING, XmlPayloadMarshaller.STRING) .payloadMarshaller(MarshallingType.INTEGER, XmlPayloadMarshaller.INTEGER) .payloadMarshaller(MarshallingType.LONG, XmlPayloadMarshaller.LONG) .payloadMarshaller(MarshallingType.SHORT, XmlPayloadMarshaller.SHORT) .payloadMarshaller(MarshallingType.FLOAT, XmlPayloadMarshaller.FLOAT) .payloadMarshaller(MarshallingType.DOUBLE, XmlPayloadMarshaller.DOUBLE) .payloadMarshaller(MarshallingType.BIG_DECIMAL, XmlPayloadMarshaller.BIG_DECIMAL) .payloadMarshaller(MarshallingType.BOOLEAN, XmlPayloadMarshaller.BOOLEAN) .payloadMarshaller(MarshallingType.INSTANT, XmlPayloadMarshaller.INSTANT) .payloadMarshaller(MarshallingType.SDK_BYTES, XmlPayloadMarshaller.SDK_BYTES) .payloadMarshaller(MarshallingType.SDK_POJO, XmlPayloadMarshaller.SDK_POJO) .payloadMarshaller(MarshallingType.LIST, XmlPayloadMarshaller.LIST) .payloadMarshaller(MarshallingType.MAP, XmlPayloadMarshaller.MAP) .payloadMarshaller(MarshallingType.NULL, XmlPayloadMarshaller.NULL) .headerMarshaller(MarshallingType.STRING, HeaderMarshaller.STRING) .headerMarshaller(MarshallingType.INTEGER, HeaderMarshaller.INTEGER) .headerMarshaller(MarshallingType.LONG, HeaderMarshaller.LONG) .headerMarshaller(MarshallingType.SHORT, HeaderMarshaller.SHORT) .headerMarshaller(MarshallingType.DOUBLE, HeaderMarshaller.DOUBLE) .headerMarshaller(MarshallingType.FLOAT, HeaderMarshaller.FLOAT) .headerMarshaller(MarshallingType.BOOLEAN, HeaderMarshaller.BOOLEAN) .headerMarshaller(MarshallingType.INSTANT, HeaderMarshaller.INSTANT) .headerMarshaller(MarshallingType.MAP, HeaderMarshaller.MAP) .headerMarshaller(MarshallingType.LIST, HeaderMarshaller.LIST) .headerMarshaller(MarshallingType.NULL, HeaderMarshaller.NULL) .queryParamMarshaller(MarshallingType.STRING, QueryParamMarshaller.STRING) .queryParamMarshaller(MarshallingType.INTEGER, QueryParamMarshaller.INTEGER) .queryParamMarshaller(MarshallingType.LONG, QueryParamMarshaller.LONG) .queryParamMarshaller(MarshallingType.SHORT, QueryParamMarshaller.SHORT) .queryParamMarshaller(MarshallingType.DOUBLE, QueryParamMarshaller.DOUBLE) .queryParamMarshaller(MarshallingType.FLOAT, QueryParamMarshaller.FLOAT) .queryParamMarshaller(MarshallingType.BOOLEAN, QueryParamMarshaller.BOOLEAN) .queryParamMarshaller(MarshallingType.INSTANT, QueryParamMarshaller.INSTANT) .queryParamMarshaller(MarshallingType.LIST, QueryParamMarshaller.LIST) .queryParamMarshaller(MarshallingType.MAP, QueryParamMarshaller.MAP) .queryParamMarshaller(MarshallingType.NULL, QueryParamMarshaller.NULL) .pathParamMarshaller(MarshallingType.STRING, SimpleTypePathMarshaller.STRING) .pathParamMarshaller(MarshallingType.INTEGER, SimpleTypePathMarshaller.INTEGER) .pathParamMarshaller(MarshallingType.LONG, SimpleTypePathMarshaller.LONG) .pathParamMarshaller(MarshallingType.SHORT, SimpleTypePathMarshaller.SHORT) .pathParamMarshaller(MarshallingType.NULL, SimpleTypePathMarshaller.NULL) .greedyPathParamMarshaller(MarshallingType.STRING, SimpleTypePathMarshaller.GREEDY_STRING) .greedyPathParamMarshaller(MarshallingType.NULL, SimpleTypePathMarshaller.NULL) .build(); } /** * @return New {@link Builder} instance. */ public static Builder builder() { return new Builder(); } /** * Builder for {@link XmlProtocolMarshaller}. */ public static final class Builder { private URI endpoint; private XmlGenerator xmlGenerator; private OperationInfo operationInfo; private Builder() { } /** * @param endpoint Endpoint to set on the marshalled request. * @return This builder for method chaining. */ public Builder endpoint(URI endpoint) { this.endpoint = endpoint; return this; } /** * @param xmlGenerator Object to write XML data. * @return This builder for method chaining. */ public Builder xmlGenerator(XmlGenerator xmlGenerator) { this.xmlGenerator = xmlGenerator; return this; } /** * @param operationInfo Metadata about the operation like URI, HTTP method, etc. * @return This builder for method chaining. */ public Builder operationInfo(OperationInfo operationInfo) { this.operationInfo = operationInfo; return this; } /** * @return New instance of {@link XmlProtocolMarshaller}. */ public XmlProtocolMarshaller build() { return new XmlProtocolMarshaller(this); } } }
2,539
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/marshall/XmlWriter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.xml.internal.marshall; import java.io.IOException; import java.io.Writer; import java.nio.ByteBuffer; import java.util.Date; import java.util.Map; import java.util.Stack; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.utils.BinaryUtils; import software.amazon.awssdk.utils.DateUtils; import software.amazon.awssdk.utils.StringUtils; /** * Utility for creating easily creating XML documents, one element at a time. */ @SdkInternalApi final class XmlWriter { /** Standard XML prolog to add to the beginning of each XML document. */ private static final String PROLOG = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; private static final String[] UNESCAPE_SEARCHES = { // Ampersands should always be the last to unescape "&quot;", "&apos;", "&lt;", "&gt;", "&#x0D;", "&#x0A;", "&amp;" }; private static final String[] UNESCAPE_REPLACEMENTS = { "\"", "'", "<", ">", "\r", "\n", "&" }; private static final String[] ESCAPE_SEARCHES = { // Ampersands should always be the first to escape "&", "\"", "'", "<", ">", "\r", "\n" }; private static final String[] ESCAPE_REPLACEMENTS = { "&amp;", "&quot;", "&apos;", "&lt;", "&gt;", "&#x0D;", "&#x0A;" }; /** The writer to which the XML document created by this writer will be written. */ private final Writer writer; /** Optional XML namespace attribute value to include in the root element. */ private final String xmlns; private Stack<String> elementStack = new Stack<>(); private boolean rootElement = true; private boolean writtenProlog = false; /** * Creates a new XMLWriter, ready to write an XML document to the specified * writer. The root element in the XML document will specify an xmlns * attribute with the specified namespace parameter. * * @param w * The writer this XMLWriter will write to. * @param xmlns * The XML namespace to include in the xmlns attribute of the * root element. */ XmlWriter(Writer w, String xmlns) { this.writer = w; this.xmlns = xmlns; } /** * Starts a new element with the specified name at the current position in * the in-progress XML document. * * @param element * The name of the new element. * * @return This XMLWriter so that additional method calls can be chained * together. */ XmlWriter startElement(String element) { // Only append the PROLOG if there is XML written. if (!writtenProlog) { writtenProlog = true; append(PROLOG); } append("<" + element); if (rootElement && xmlns != null) { append(" xmlns=\"" + xmlns + "\""); rootElement = false; } append(">"); elementStack.push(element); return this; } /** * Start to write an element with xml attributes. * * @param element the elment to write * @param attributes the xml attribtues * @return the XmlWriter */ XmlWriter startElement(String element, Map<String, String> attributes) { append("<" + element); for (Map.Entry<String, String> attribute: attributes.entrySet()) { append(" " + attribute.getKey() + "=\"" + attribute.getValue() + "\""); } append(">"); elementStack.push(element); return this; } /** * Closes the last opened element at the current position in the in-progress * XML document. * * @return This XMLWriter so that additional method calls can be chained * together. */ XmlWriter endElement() { String lastElement = elementStack.pop(); append("</" + lastElement + ">"); return this; } /** * Adds the specified value as text to the current position of the in * progress XML document. * * @param s * The text to add to the XML document. * * @return This XMLWriter so that additional method calls can be chained * together. */ public XmlWriter value(String s) { append(escapeXmlEntities(s)); return this; } /** * Adds the specified value as Base64 encoded text to the current position of the in * progress XML document. * * @param b * The binary data to add to the XML document. * * @return This XMLWriter so that additional method calls can be chained * together. */ public XmlWriter value(ByteBuffer b) { append(escapeXmlEntities(BinaryUtils.toBase64(BinaryUtils.copyBytesFrom(b)))); return this; } /** * Adds the specified date as text to the current position of the * in-progress XML document. * * @param date * The date to add to the XML document. * * @return This XMLWriter so that additional method calls can be chained * together. */ public XmlWriter value(Date date) { append(escapeXmlEntities(DateUtils.formatIso8601Date(date.toInstant()))); return this; } /** * Adds the string representation of the specified object to the current * position of the in progress XML document. * * @param obj * The object to translate to a string and add to the XML * document. * * @return This XMLWriter so that additional method calls can be chained * together. */ public XmlWriter value(Object obj) { append(escapeXmlEntities(obj.toString())); return this; } private void append(String s) { try { writer.append(s); } catch (IOException e) { throw SdkClientException.builder().message("Unable to write XML document").cause(e).build(); } } private String escapeXmlEntities(String s) { // Unescape any escaped characters. if (s.contains("&")) { s = StringUtils.replaceEach(s, UNESCAPE_SEARCHES, UNESCAPE_REPLACEMENTS); } return StringUtils.replaceEach(s, ESCAPE_SEARCHES, ESCAPE_REPLACEMENTS); } }
2,540
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/marshall/QueryParamMarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.xml.internal.marshall; import java.time.Instant; import java.util.List; import java.util.Map; import java.util.Objects; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.protocol.MarshallLocation; import software.amazon.awssdk.core.traits.ListTrait; import software.amazon.awssdk.core.traits.MapTrait; import software.amazon.awssdk.core.traits.RequiredTrait; import software.amazon.awssdk.protocols.core.ValueToStringConverter; @SdkInternalApi public final class QueryParamMarshaller { public static final XmlMarshaller<String> STRING = new SimpleQueryParamMarshaller<>(ValueToStringConverter.FROM_STRING); public static final XmlMarshaller<Integer> INTEGER = new SimpleQueryParamMarshaller<>(ValueToStringConverter.FROM_INTEGER); public static final XmlMarshaller<Long> LONG = new SimpleQueryParamMarshaller<>(ValueToStringConverter.FROM_LONG); public static final XmlMarshaller<Short> SHORT = new SimpleQueryParamMarshaller<>(ValueToStringConverter.FROM_SHORT); public static final XmlMarshaller<Double> DOUBLE = new SimpleQueryParamMarshaller<>(ValueToStringConverter.FROM_DOUBLE); public static final XmlMarshaller<Float> FLOAT = new SimpleQueryParamMarshaller<>(ValueToStringConverter.FROM_FLOAT); public static final XmlMarshaller<Boolean> BOOLEAN = new SimpleQueryParamMarshaller<>(ValueToStringConverter.FROM_BOOLEAN); public static final XmlMarshaller<Instant> INSTANT = new SimpleQueryParamMarshaller<>(XmlProtocolMarshaller.INSTANT_VALUE_TO_STRING); public static final XmlMarshaller<List<?>> LIST = (list, context, paramName, sdkField) -> { if (list == null || list.isEmpty()) { return; } for (Object member : list) { context.marshall(MarshallLocation.QUERY_PARAM, member, paramName, null); } }; public static final XmlMarshaller<Map<String, ?>> MAP = (map, context, paramName, sdkField) -> { if (map == null || map.isEmpty()) { return; } MapTrait mapTrait = sdkField.getRequiredTrait(MapTrait.class); SdkField valueField = mapTrait.valueFieldInfo(); for (Map.Entry<String, ?> entry : map.entrySet()) { if (valueField.containsTrait(ListTrait.class)) { ((List<?>) entry.getValue()).forEach(val -> { context.marshallerRegistry().getMarshaller(MarshallLocation.QUERY_PARAM, val) .marshall(val, context, entry.getKey(), null); }); } else { SimpleQueryParamMarshaller valueMarshaller = (SimpleQueryParamMarshaller) context.marshallerRegistry().getMarshaller(MarshallLocation.QUERY_PARAM, entry.getValue()); context.request().putRawQueryParameter(entry.getKey(), valueMarshaller.convert(entry.getValue(), null)); } } }; public static final XmlMarshaller<Void> NULL = (val, context, paramName, sdkField) -> { if (Objects.nonNull(sdkField) && sdkField.containsTrait(RequiredTrait.class)) { throw new IllegalArgumentException(String.format("Parameter '%s' must not be null", paramName)); } }; private QueryParamMarshaller() { } private static class SimpleQueryParamMarshaller<T> implements XmlMarshaller<T> { private final ValueToStringConverter.ValueToString<T> converter; private SimpleQueryParamMarshaller(ValueToStringConverter.ValueToString<T> converter) { this.converter = converter; } @Override public void marshall(T val, XmlMarshallerContext context, String paramName, SdkField<T> sdkField) { context.request().appendRawQueryParameter(paramName, converter.convert(val, sdkField)); } public String convert(T val, SdkField<T> sdkField) { return converter.convert(val, sdkField); } } }
2,541
0
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal
Create_ds/aws-sdk-java-v2/core/protocols/aws-xml-protocol/src/main/java/software/amazon/awssdk/protocols/xml/internal/marshall/XmlMarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.xml.internal.marshall; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.protocols.core.Marshaller; /** * Interface to marshall data for xml protocol * * @param <T> Type to marshall. */ @FunctionalInterface @SdkInternalApi public interface XmlMarshaller<T> extends Marshaller<T> { XmlMarshaller<Void> NULL = (val, context, paramName, sdkField) -> { }; void marshall(T val, XmlMarshallerContext context, String paramName, SdkField<T> sdkField); }
2,542
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/TestUtils.java
package software.amazon.awssdk.http.auth.aws; import static software.amazon.awssdk.http.auth.aws.signer.AwsV4HttpSigner.REGION_NAME; import static software.amazon.awssdk.http.auth.aws.signer.AwsV4HttpSigner.SERVICE_SIGNING_NAME; import static software.amazon.awssdk.http.auth.spi.signer.HttpSigner.SIGNING_CLOCK; import java.io.ByteArrayInputStream; import java.net.URI; import java.nio.ByteBuffer; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.time.ZoneId; import java.time.ZoneOffset; import java.util.function.Consumer; 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.SignRequest; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.utils.async.SimplePublisher; public final class TestUtils { private TestUtils() { } // Helpers for generating test requests public static <T extends AwsCredentialsIdentity> SignRequest<T> generateBasicRequest( T credentials, Consumer<? super SdkHttpRequest.Builder> requestOverrides, Consumer<? super SignRequest.Builder<T>> signRequestOverrides ) { return SignRequest.builder(credentials) .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("https://demo.us-east-1.amazonaws.com")) .build() .copy(requestOverrides)) .payload(() -> new ByteArrayInputStream("{\"TableName\": \"foo\"}".getBytes())) .putProperty(REGION_NAME, "us-east-1") .putProperty(SERVICE_SIGNING_NAME, "demo") .putProperty(SIGNING_CLOCK, new TickingClock(Instant.ofEpochMilli(351153000968L))) .build() .copy(signRequestOverrides); } public static <T extends AwsCredentialsIdentity> AsyncSignRequest<T> generateBasicAsyncRequest( T credentials, Consumer<? super SdkHttpRequest.Builder> requestOverrides, Consumer<? super AsyncSignRequest.Builder<T>> signRequestOverrides ) { SimplePublisher<ByteBuffer> publisher = new SimplePublisher<>(); publisher.send(ByteBuffer.wrap("{\"TableName\": \"foo\"}".getBytes())); publisher.complete(); return AsyncSignRequest.builder(credentials) .request(SdkHttpRequest.builder() .protocol("https") .method(SdkHttpMethod.POST) .putHeader("Host", "demo.us-east-1.amazonaws.com") .putHeader("x-amz-archive-description", "test test") .encodedPath("/") .uri(URI.create("https://demo.us-east-1.amazonaws.com")) .build() .copy(requestOverrides)) .payload(publisher) .putProperty(REGION_NAME, "us-east-1") .putProperty(SERVICE_SIGNING_NAME, "demo") .putProperty(SIGNING_CLOCK, new TickingClock(Instant.ofEpochMilli(351153000968L))) .build() .copy(signRequestOverrides); } public static class AnonymousCredentialsIdentity implements AwsCredentialsIdentity { @Override public String accessKeyId() { return null; } @Override public String secretAccessKey() { return null; } } public static class TickingClock extends Clock { private final Duration tick = Duration.ofSeconds(1); private Instant time; public TickingClock(Instant time) { this.time = time; } @Override public ZoneId getZone() { return ZoneOffset.UTC; } @Override public Clock withZone(ZoneId zone) { throw new UnsupportedOperationException(); } @Override public Instant instant() { Instant time = this.time; this.time = time.plus(tick); return time; } } }
2,543
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/AwsV4aHttpSignerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; import static org.junit.jupiter.api.Assertions.assertThrows; import org.assertj.core.api.AssertionsForClassTypes; import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; import software.amazon.awssdk.http.auth.aws.signer.AwsV4aHttpSigner; import software.amazon.awssdk.utils.ClassLoaderHelper; public class AwsV4aHttpSignerTest { @Test public void create_WithoutHttpAuthAwsCrtModule_throws() { try (MockedStatic<ClassLoaderHelper> utilities = Mockito.mockStatic(ClassLoaderHelper.class)) { utilities.when(() -> ClassLoaderHelper.loadClass( "software.amazon.awssdk.http.auth.aws.crt.HttpAuthAwsCrt", false) ).thenThrow(new ClassNotFoundException("boom!")); Exception e = assertThrows(RuntimeException.class, AwsV4aHttpSigner::create); AssertionsForClassTypes.assertThat(e).hasMessageContaining("http-auth-aws-crt"); } } }
2,544
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/RegionSetTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertIterableEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.fail; import static software.amazon.awssdk.http.auth.aws.RegionSetTest.Case.tc; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import software.amazon.awssdk.http.auth.aws.signer.RegionSet; public class RegionSetTest { private static final List<Case<String>> stringCaseList = Arrays.asList( tc("*", "*", Arrays.asList("*")), tc("us-west-2", "us-west-2", Arrays.asList("us-west-2")), tc("us-east-1,us-west-2", "us-east-1,us-west-2", Arrays.asList("us-east-1", "us-west-2")), tc(" us-west-2 ", "us-west-2", Arrays.asList("us-west-2")), tc(" us-east-1, us-west-2 ", "us-east-1,us-west-2", Arrays.asList("us-east-1", "us-west-2")), tc(" a,b ,c ,d ,e ,f , g ", "a,b,c,d,e,f,g", Arrays.asList("a", "b", "c", "d", "e", "f", "g")) ); private static final List<String> stringFailList = Arrays.asList( null, "", " ", ", ,", ",,," ); private static final List<Case<Collection<String>>> collectionCaseList = Arrays.asList( tc(Arrays.asList("*"), "*", Arrays.asList("*")), tc(Arrays.asList("us-west-2"), "us-west-2", Arrays.asList("us-west-2")), tc(Arrays.asList("us-east-1", "us-west-2"), "us-east-1,us-west-2", Arrays.asList("us-east-1", "us-west-2")), tc(Arrays.asList(" us-west-2 "), "us-west-2", Arrays.asList("us-west-2")), tc(Arrays.asList(" us-east-1", " us-west-2 "), "us-east-1,us-west-2", Arrays.asList("us-east-1", "us-west-2")), tc(Arrays.asList(" a", "b ", "c ", "d ", "e ", "f ", " g "), "a,b,c,d,e,f,g", Arrays.asList("a", "b", "c", "d", "e", "f", "g") ) ); private static final List<Collection<String>> collectionFailList = Arrays.asList( null, Arrays.asList(), Arrays.asList(""), Arrays.asList(" "), Arrays.asList(" ", ""), Arrays.asList("", "", "") ); private static List<Case<String>> stringCases() { return stringCaseList; } private static List<String> stringFailures() { return stringFailList; } private static List<Case<Collection<String>>> collectionCases() { return collectionCaseList; } private static List<Collection<String>> collectionFailures() { return collectionFailList; } @ParameterizedTest @MethodSource("stringCases") public void create_withStringInput_succeeds(Case<String> stringCase) { RegionSet regionSet = RegionSet.create(stringCase.input); assertEquals(stringCase.asString, regionSet.asString()); assertIterableEquals(stringCase.asSet, regionSet.asSet()); } @ParameterizedTest @MethodSource("stringFailures") public void create_withInvalidStringInput_throws(String input) { Exception ex = assertThrows(Exception.class, () -> RegionSet.create(input)); if (ex instanceof NullPointerException) { assertThat(ex.getMessage()).contains("must not be"); } else if (ex instanceof IllegalArgumentException) { assertThat(ex.getMessage()).contains("must not be"); } else { fail(); } } @ParameterizedTest @MethodSource("collectionCases") public void create_withCollectionInput_succeeds(Case<Collection<String>> collectionCase) { RegionSet regionSet = RegionSet.create(collectionCase.input); assertEquals(collectionCase.asString, regionSet.asString()); assertIterableEquals(collectionCase.asSet, regionSet.asSet()); } @ParameterizedTest @MethodSource("collectionFailures") public void create_withInvalidCollectionInput_throws(Collection<String> input) { Exception ex = assertThrows(Exception.class, () -> RegionSet.create(input)); if (ex instanceof NullPointerException) { assertThat(ex.getMessage()).contains("must not be"); } else if (ex instanceof IllegalArgumentException) { assertThat(ex.getMessage()).contains("must not be"); } else { fail(); } } static final class Case<T> { final T input; final String asString; final Collection<String> asSet; private Case(T input, String asString, Collection<String> asSet) { this.input = input; this.asString = asString; this.asSet = asSet; } static <T> Case<T> tc(T input, String asString, Collection<String> asSet) { return new Case<>(input, asString, asSet); } @Override public String toString() { return String.format("%s => %s :: %s", input, asString, asSet); } } }
2,545
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/eventstream/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/eventstream/internal/io/SigV4DataFramePublisherTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.eventstream.internal.io; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import io.reactivex.Flowable; import io.reactivex.functions.BiFunction; import io.reactivex.functions.Function; import io.reactivex.subscribers.TestSubscriber; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.time.Clock; import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneId; import java.time.ZoneOffset; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import java.util.stream.Stream; import org.assertj.core.util.Lists; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.http.auth.aws.internal.signer.CredentialScope; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.utils.BinaryUtils; import software.amazon.eventstream.HeaderValue; import software.amazon.eventstream.Message; import software.amazon.eventstream.MessageDecoder; public class SigV4DataFramePublisherTest { private static final List<Instant> SIGNING_INSTANTS = Stream.of( // Note: This first Instant is used for signing the request not an event OffsetDateTime.of(1981, 1, 16, 6, 30, 0, 0, ZoneOffset.UTC).toInstant(), OffsetDateTime.of(1981, 1, 16, 6, 30, 1, 0, ZoneOffset.UTC).toInstant(), OffsetDateTime.of(1981, 1, 16, 6, 30, 2, 0, ZoneOffset.UTC).toInstant(), OffsetDateTime.of(1981, 1, 16, 6, 30, 3, 0, ZoneOffset.UTC).toInstant(), OffsetDateTime.of(1981, 1, 16, 6, 30, 4, 0, ZoneOffset.UTC).toInstant() ).collect(Collectors.toList()); /** * @return A clock that returns the values from {@link #SIGNING_INSTANTS} in order. * @throws IllegalStateException When there are no more instants to return. */ private static Clock signingClock() { return new Clock() { private final AtomicInteger timeIndex = new AtomicInteger(0); @Override public Instant instant() { int idx = timeIndex.getAndIncrement(); // Note: we use an atomic because Clock must be threadsafe, // though probably not necessary for our tests if (idx >= SIGNING_INSTANTS.size()) { throw new IllegalStateException("Clock ran out of Instants to return! " + idx); } return SIGNING_INSTANTS.get(idx); } @Override public ZoneId getZone() { return ZoneOffset.UTC; } @Override public Clock withZone(ZoneId zone) { throw new UnsupportedOperationException(); } }; } /** * Test that the sigv4 publisher adapts an existing publisher with sigv4 chunk-signing */ @Test public void sigV4DataFramePublisher_shouldAdaptAndSignPublisher() { TestVector testVector = generateTestVector(); Clock signingClock = signingClock(); Instant initialInstant = signingClock.instant(); AwsCredentialsIdentity credentials = AwsCredentialsIdentity.create("access", "secret"); CredentialScope credentialScope = new CredentialScope("us-east-1", "demo", initialInstant); Publisher<ByteBuffer> sigV4Publisher = SigV4DataFramePublisher.builder() .publisher(testVector.payload()) .credentials(credentials) .credentialScope(credentialScope) .signature(testVector.signature()) .signingClock(signingClock) .build(); TestSubscriber testSubscriber = TestSubscriber.create(); Flowable.fromPublisher(sigV4Publisher) .flatMap(new Function<ByteBuffer, Publisher<?>>() { final Queue<Message> messages = new LinkedList<>(); final MessageDecoder decoder = new MessageDecoder(message -> messages.offer(message)); @Override public Publisher<?> apply(ByteBuffer byteBuffer) { decoder.feed(byteBuffer.array()); List<Message> messageList = new ArrayList<>(); while (!messages.isEmpty()) { messageList.add(messages.poll()); } return Flowable.fromIterable(messageList); } }) .subscribe(testSubscriber); testSubscriber.assertNoErrors(); testSubscriber.assertComplete(); testSubscriber.assertValueSequence(testVector.expectedPublisher().blockingIterable()); } /** * Test that without demand from subscriber, trailing empty frame is not delivered */ @Test public void testBackPressure() { TestVector testVector = generateTestVector(); Clock signingClock = signingClock(); Instant initialInstant = signingClock.instant(); AwsCredentialsIdentity credentials = AwsCredentialsIdentity.create("access", "secret"); CredentialScope credentialScope = new CredentialScope("us-east-1", "demo", initialInstant); Publisher<ByteBuffer> sigV4Publisher = SigV4DataFramePublisher.builder() .publisher(testVector.payload()) .credentials(credentials) .credentialScope(credentialScope) .signature(testVector.signature()) .signingClock(signingClock) .build(); Subscriber<Object> subscriber = Mockito.spy(new Subscriber<Object>() { @Override public void onSubscribe(Subscription s) { // Only request the size of request body (which should NOT include the empty frame) s.request(testVector.content().size()); } @Override public void onNext(Object o) { } @Override public void onError(Throwable t) { fail("onError should never been called"); } @Override public void onComplete() { fail("onComplete should never been called"); } }); Flowable.fromPublisher(sigV4Publisher) .flatMap(new Function<ByteBuffer, Publisher<?>>() { final Queue<Message> messages = new LinkedList<>(); final MessageDecoder decoder = new MessageDecoder(message -> messages.offer(message)); @Override public Publisher<?> apply(ByteBuffer byteBuffer) throws Exception { decoder.feed(byteBuffer.array()); List<Message> messageList = new ArrayList<>(); while (!messages.isEmpty()) { messageList.add(messages.poll()); } return Flowable.fromIterable(messageList); } }) .subscribe(subscriber); // The number of events equal to the size of request body (excluding trailing empty frame) verify(subscriber, times(testVector.content().size())).onNext(any()); // subscriber is not terminated (no onError/onComplete) since trailing empty frame is not delivered yet verify(subscriber, never()).onError(any()); verify(subscriber, never()).onComplete(); } private TestVector generateTestVector() { return new TestVector() { final List<String> content = Lists.newArrayList("A", "B", "C"); @Override public List<String> content() { return content; } @Override public String signature() { return "e1d8e8c8815e60969f2a34765c9a15945ffc0badbaa4b7e3b163ea19131e949b"; } @Override public Publisher<ByteBuffer> payload() { List<ByteBuffer> bodyBytes = content.stream() .map(s -> ByteBuffer.wrap(s.getBytes(StandardCharsets.UTF_8))) .collect(Collectors.toList()); return Flowable.fromIterable(bodyBytes); } @Override public Flowable<Message> expectedPublisher() { Flowable<String> sigsHex = Flowable.just( "7aabf85b765e6a4d0d500b6e968657b14726fa3e1eb7e839302728ffd77629a5", "f72aa9642f571d24a6e1ae42f10f073ad9448d8a028b6bcd82da081335adda02", "632af120435b57ec241d8bfbb12e496dfd5e2730a1a02ac0ab6eaa230ae02e9a", "c6f679ddb3af68f5e82f0cf6761244cb2338cf11e7d01a24130aea1b7c17e53e"); // The Last data frame is empty Flowable<String> payloads = Flowable.fromIterable(content).concatWith(Flowable.just("")); return sigsHex.zipWith(payloads, new BiFunction<String, String, Message>() { // The first Instant was used to sign the request private int idx = 1; @Override public Message apply(String sig, String payload) { Map<String, HeaderValue> headers = new HashMap<>(); headers.put(":date", HeaderValue.fromTimestamp(SIGNING_INSTANTS.get(idx))); headers.put(":chunk-signature", HeaderValue.fromByteArray(BinaryUtils.fromHex(sig))); idx += 1; return new Message(headers, payload.getBytes(StandardCharsets.UTF_8)); } } ); } }; } private interface TestVector { String signature(); List<String> content(); Publisher<ByteBuffer> payload(); Flowable<Message> expectedPublisher(); } }
2,546
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/eventstream/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/eventstream/internal/io/SigV4DataFramePublisherTckTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.eventstream.internal.io; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.time.Clock; import java.time.Instant; import org.reactivestreams.Publisher; import org.reactivestreams.tck.PublisherVerification; import org.reactivestreams.tck.TestEnvironment; import software.amazon.awssdk.http.auth.aws.TestUtils.TickingClock; import software.amazon.awssdk.http.auth.aws.internal.signer.CredentialScope; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.utils.async.SimplePublisher; public class SigV4DataFramePublisherTckTest extends PublisherVerification<ByteBuffer> { public SigV4DataFramePublisherTckTest() { super(new TestEnvironment()); } @Override public Publisher<ByteBuffer> createPublisher(long elements) { Clock signingClock = new TickingClock(Instant.EPOCH); Instant initialInstant = signingClock.instant(); AwsCredentialsIdentity credentials = AwsCredentialsIdentity.create("access", "secret"); CredentialScope credentialScope = new CredentialScope("us-east-1", "demo", initialInstant); SimplePublisher<ByteBuffer> payload = new SimplePublisher<>(); Publisher<ByteBuffer> sigV4Publisher = SigV4DataFramePublisher.builder() .publisher(payload) .credentials(credentials) .credentialScope(credentialScope) .signature("signature") .signingClock(signingClock) .build(); // since this publisher specifically appends an empty element to the end, we need to subtract 1 // from the number of elements to expected to be "produced" before end-of-stream long expectedElements = elements - 1; for (int i = 0; i < expectedElements; i++) { payload.send(ByteBuffer.wrap(Integer.toString(i).getBytes(StandardCharsets.UTF_8))); } payload.complete(); return sigV4Publisher; } @Override public Publisher<ByteBuffer> createFailedPublisher() { Clock signingClock = new TickingClock(Instant.EPOCH); Instant initialInstant = signingClock.instant(); AwsCredentialsIdentity credentials = AwsCredentialsIdentity.create("access", "secret"); CredentialScope credentialScope = new CredentialScope("us-east-1", "demo", initialInstant); SimplePublisher<ByteBuffer> payload = new SimplePublisher<>(); Publisher<ByteBuffer> sigV4Publisher = SigV4DataFramePublisher.builder() .publisher(payload) .credentials(credentials) .credentialScope(credentialScope) .signature("signature") .signingClock(signingClock) .build(); payload.error(new RuntimeException("boom!")); return sigV4Publisher; } @Override public long maxElementsFromPublisher() { return 256L; } }
2,547
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer/DefaultRequestSignerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.signer; import static java.time.ZoneOffset.UTC; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static software.amazon.awssdk.utils.BinaryUtils.toHex; import java.net.URI; import java.time.Clock; import java.time.Instant; import org.junit.jupiter.api.Test; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; public class DefaultRequestSignerTest { V4Properties v4Properties = V4Properties.builder() .credentials(AwsCredentialsIdentity.create("foo", "bar")) .credentialScope(new CredentialScope("baz", "qux", Instant.EPOCH)) .signingClock(Clock.fixed(Instant.EPOCH, UTC)) .doubleUrlEncode(true) .normalizePath(true) .build(); DefaultV4RequestSigner requestSigner = new DefaultV4RequestSigner(v4Properties, "quux"); @Test public void requestSigner_sign_shouldReturnSignedResult_butNotAddAnyAuthInfoToRequest() { SdkHttpRequest.Builder request = SdkHttpRequest .builder() .uri(URI.create("https://localhost")) .method(SdkHttpMethod.GET) .putHeader("Host", "localhost"); String expectedContentHash = "quux"; String expectedSigningKeyHex = "3d558b7a87b67996abc908071e0771a31b2a7977ab247144e60a6cba3356be1f"; String expectedSignature = "6c1f4222e0888e6e68b20ded382bc80c7312465c69fb52cbd6d6ce2d073533bf"; String expectedCanonicalRequestString = "GET\n/\n\n" + "host:localhost\n\n" + "host\nquux"; String expectedHost = "localhost"; V4RequestSigningResult requestSigningResult = requestSigner.sign(request); assertEquals(expectedContentHash, requestSigningResult.getContentHash()); assertEquals(expectedSigningKeyHex, toHex(requestSigningResult.getSigningKey())); assertEquals(expectedSignature, requestSigningResult.getSignature()); assertEquals(expectedCanonicalRequestString, requestSigningResult.getCanonicalRequest().getCanonicalRequestString()); assertEquals(expectedHost, requestSigningResult.getSignedRequest().firstMatchingHeader("Host").orElse("")); assertThat(requestSigningResult.getSignedRequest().build()).usingRecursiveComparison().isEqualTo(request.build()); } }
2,548
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer/DefaultAwsV4HttpSignerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.signer; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import static software.amazon.awssdk.checksums.DefaultChecksumAlgorithm.CRC32; import static software.amazon.awssdk.http.auth.aws.TestUtils.generateBasicAsyncRequest; import static software.amazon.awssdk.http.auth.aws.TestUtils.generateBasicRequest; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerConstant.CONTENT_ENCODING; import static software.amazon.awssdk.http.auth.aws.signer.AwsV4HttpSigner.AUTH_LOCATION; import static software.amazon.awssdk.http.auth.aws.signer.AwsV4HttpSigner.CHECKSUM_ALGORITHM; import static software.amazon.awssdk.http.auth.aws.signer.AwsV4HttpSigner.CHUNK_ENCODING_ENABLED; import static software.amazon.awssdk.http.auth.aws.signer.AwsV4HttpSigner.EXPIRATION_DURATION; import static software.amazon.awssdk.http.auth.aws.signer.AwsV4HttpSigner.PAYLOAD_SIGNING_ENABLED; import java.net.URI; import java.time.Duration; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.MockedStatic; import org.mockito.Mockito; import software.amazon.awssdk.http.Header; import software.amazon.awssdk.http.auth.aws.TestUtils; import software.amazon.awssdk.http.auth.aws.eventstream.internal.io.SigV4DataFramePublisher; import software.amazon.awssdk.http.auth.aws.signer.AwsV4FamilyHttpSigner.AuthLocation; 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.AwsCredentialsIdentity; import software.amazon.awssdk.utils.ClassLoaderHelper; /** * Test the delegation of signing to the correct implementations. */ public class DefaultAwsV4HttpSignerTest { DefaultAwsV4HttpSigner signer = new DefaultAwsV4HttpSigner(); @Test public void sign_WithNoAdditonalProperties_DelegatesToHeaderSigner() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> { }, signRequest -> { } ); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingHeader("Authorization")).isPresent(); } @Test public void signAsync_WithNoAdditonalProperties_DelegatesToHeaderSigner() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> { }, signRequest -> { } ); AsyncSignedRequest signedRequest = signer.signAsync(request).join(); assertThat(signedRequest.request().firstMatchingHeader("Authorization")).isPresent(); } @Test public void sign_WithQueryAuthLocation_DelegatesToQuerySigner() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> { }, signRequest -> signRequest.putProperty(AUTH_LOCATION, AuthLocation.QUERY_STRING) ); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingRawQueryParameter("X-Amz-Signature")).isPresent(); } @Test public void signAsync_WithQueryAuthLocation_DelegatesToQuerySigner() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> { }, signRequest -> signRequest.putProperty(AUTH_LOCATION, AuthLocation.QUERY_STRING) ); AsyncSignedRequest signedRequest = signer.signAsync(request).join(); assertThat(signedRequest.request().firstMatchingRawQueryParameter("X-Amz-Signature")).isPresent(); } @ParameterizedTest @ValueSource(longs = {-1, 0, 604801}) public void sign_WithQueryAuthLocationAndInvalidExpiration_Throws(long seconds) { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> { }, signRequest -> signRequest .putProperty(AUTH_LOCATION, AuthLocation.QUERY_STRING) .putProperty(EXPIRATION_DURATION, Duration.ofSeconds(seconds)) ); assertThrows(IllegalArgumentException.class, () -> signer.sign(request)); } @ParameterizedTest @ValueSource(longs = {-1, 0, 604801}) public void signAsync_WithQueryAuthLocationAndInvalidExpiration_Throws(long seconds) { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> { }, signRequest -> signRequest .putProperty(AUTH_LOCATION, AuthLocation.QUERY_STRING) .putProperty(EXPIRATION_DURATION, Duration.ofSeconds(seconds)) ); assertThrows(IllegalArgumentException.class, () -> signer.signAsync(request)); } @Test public void sign_WithQueryAuthLocationAndExpiration_DelegatesToPresignedSigner() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> { }, signRequest -> signRequest .putProperty(AUTH_LOCATION, AuthLocation.QUERY_STRING) .putProperty(EXPIRATION_DURATION, Duration.ofDays(1)) ); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingRawQueryParameter("X-Amz-Expires")).isPresent(); } @Test public void signAsync_WithQueryAuthLocationAndExpiration_DelegatesToPresignedSigner() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> { }, signRequest -> signRequest .putProperty(AUTH_LOCATION, AuthLocation.QUERY_STRING) .putProperty(EXPIRATION_DURATION, Duration.ofDays(1)) ); AsyncSignedRequest signedRequest = signer.signAsync(request).join(); assertThat(signedRequest.request().firstMatchingRawQueryParameter("X-Amz-Expires")).isPresent(); } @Test public void sign_WithHeaderAuthLocationAndExpirationDuration_Throws() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> { }, signRequest -> signRequest .putProperty(AUTH_LOCATION, AuthLocation.HEADER) .putProperty(EXPIRATION_DURATION, Duration.ofDays(1)) ); assertThrows(UnsupportedOperationException.class, () -> signer.sign(request)); } @Test public void signAsync_WithHeaderAuthLocationAndExpirationDuration_Throws() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> { }, signRequest -> signRequest .putProperty(AUTH_LOCATION, AuthLocation.HEADER) .putProperty(EXPIRATION_DURATION, Duration.ofDays(1)) ); assertThrows(UnsupportedOperationException.class, () -> signer.signAsync(request).join()); } @Test public void sign_withAnonymousCreds_shouldNotSign() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( new TestUtils.AnonymousCredentialsIdentity(), httpRequest -> { }, signRequest -> { } ); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingRawQueryParameter("X-Amz-Signature")) .isNotPresent(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")).isNotPresent(); } @Test public void signAsync_withAnonymousCreds_shouldNotSign() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( new TestUtils.AnonymousCredentialsIdentity(), httpRequest -> { }, signRequest -> { } ); AsyncSignedRequest signedRequest = signer.signAsync(request).join(); assertThat(signedRequest.request().firstMatchingRawQueryParameter("X-Amz-Signature")) .isNotPresent(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")).isNotPresent(); } @Test public void sign_WithPayloadSigningFalse_DelegatesToUnsignedPayloadSigner() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> { }, signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, false) ); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")).hasValue("UNSIGNED-PAYLOAD"); } @Test public void signAsync_WithPayloadSigningFalse_DelegatesToUnsignedPayloadSigner() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> { }, signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, false) ); AsyncSignedRequest signedRequest = signer.signAsync(request).join(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")).hasValue("UNSIGNED-PAYLOAD"); } @Test public void sign_WithEventStreamContentTypeWithoutHttpAuthAwsEventStreamModule_throws() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader("Content-Type", "application/vnd.amazon.eventstream"), signRequest -> { } ); try (MockedStatic<ClassLoaderHelper> utilities = Mockito.mockStatic(ClassLoaderHelper.class)) { utilities.when(() ->ClassLoaderHelper.loadClass( "software.amazon.awssdk.http.auth.aws.eventstream.HttpAuthAwsEventStream", false) ).thenThrow(new ClassNotFoundException("boom!")); Exception e = assertThrows(RuntimeException.class, () -> signer.sign(request)); assertThat(e).hasMessageContaining("http-auth-aws-eventstream"); } } @Test public void signAsync_WithEventStreamContentTypeWithoutHttpAuthAwsEventStreamModule_throws() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader("Content-Type", "application/vnd.amazon.eventstream"), signRequest -> { } ); try (MockedStatic<ClassLoaderHelper> utilities = Mockito.mockStatic(ClassLoaderHelper.class)) { utilities.when(() ->ClassLoaderHelper.loadClass( "software.amazon.awssdk.http.auth.aws.eventstream.HttpAuthAwsEventStream", false) ).thenThrow(new ClassNotFoundException("boom!")); Exception e = assertThrows(RuntimeException.class, () -> signer.signAsync(request).join()); assertThat(e).hasMessageContaining("http-auth-aws-eventstream"); } } @Test public void sign_WithEventStreamContentType_Throws() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader("Content-Type", "application/vnd.amazon.eventstream"), signRequest -> { } ); assertThrows(UnsupportedOperationException.class, () -> signer.sign(request)); } @Test public void signAsync_WithEventStreamContentType_DelegatesToEventStreamPayloadSigner() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader("Content-Type", "application/vnd.amazon.eventstream"), signRequest -> { } ); AsyncSignedRequest signedRequest = signer.signAsync(request).join(); assertThat(signedRequest.payload().get()).isInstanceOf(SigV4DataFramePublisher.class); } @Test public void sign_WithEventStreamContentTypeAndUnsignedPayload_Throws() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader("Content-Type", "application/vnd.amazon.eventstream"), signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, false) ); assertThrows(UnsupportedOperationException.class, () -> signer.sign(request)); } @Test public void signAsync_WithEventStreamContentTypeAndUnsignedPayload_Throws() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader("Content-Type", "application/vnd.amazon.eventstream"), signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, false) ); assertThrows(UnsupportedOperationException.class, () -> signer.signAsync(request)); } @Test public void sign_WithChunkEncodingTrue_DelegatesToAwsChunkedPayloadSigner() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader(Header.CONTENT_LENGTH, "20"), signRequest -> signRequest .putProperty(CHUNK_ENCODING_ENABLED, true) ); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")) .hasValue("STREAMING-AWS4-HMAC-SHA256-PAYLOAD"); assertThat(signedRequest.request().firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue("193"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-decoded-content-length")).hasValue("20"); } // TODO(sra-identity-and-auth): Once chunk-encoding support in async is added, we can enable these tests. @Disabled("Chunk-encoding is not currently supported in the Async signing path - it is handled in HttpChecksumStage for now.") @Test public void signAsync_WithChunkEncodingTrue_DelegatesToAwsChunkedPayloadSigner_futureBehavior() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader(Header.CONTENT_LENGTH, "20"), signRequest -> signRequest .putProperty(CHUNK_ENCODING_ENABLED, true) ); AsyncSignedRequest signedRequest = signer.signAsync(request).join(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")) .hasValue("STREAMING-AWS4-HMAC-SHA256-PAYLOAD"); assertThat(signedRequest.request().firstMatchingHeader(CONTENT_ENCODING)).hasValue("aws-chunked"); assertThat(signedRequest.request().firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue("193"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-decoded-content-length")).hasValue("20"); } // TODO(sra-identity-and-auth): Replace this test with the above test once chunk-encoding support is added @Test public void signAsync_WithChunkEncodingTrue_DelegatesToAwsChunkedPayloadSigner() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader(Header.CONTENT_LENGTH, "20"), signRequest -> signRequest .putProperty(CHUNK_ENCODING_ENABLED, true) ); AsyncSignedRequest signedRequest = signer.signAsync(request).join(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")) .hasValue("STREAMING-AWS4-HMAC-SHA256-PAYLOAD"); assertThat(signedRequest.request().firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue("20"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-decoded-content-length")).isNotPresent(); } @Test public void sign_WithChunkEncodingTrueAndChecksumAlgorithm_DelegatesToAwsChunkedPayloadSigner() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader(Header.CONTENT_LENGTH, "20"), signRequest -> signRequest .putProperty(CHUNK_ENCODING_ENABLED, true) .putProperty(CHECKSUM_ALGORITHM, CRC32) ); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")) .hasValue("STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER"); assertThat(signedRequest.request().firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue("314"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-decoded-content-length")).hasValue("20"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-trailer")).hasValue("x-amz-checksum-crc32"); } // TODO(sra-identity-and-auth): Once chunk-encoding support in async is added, we can enable these tests. @Disabled("Chunk-encoding is not currently supported in the Async signing path - it is handled in HttpChecksumStage for now.") @Test public void signAsync_WithChunkEncodingTrueAndChecksumAlgorithm_DelegatesToAwsChunkedPayloadSigner_futureBehavior() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader(Header.CONTENT_LENGTH, "20"), signRequest -> signRequest .putProperty(CHUNK_ENCODING_ENABLED, true) .putProperty(CHECKSUM_ALGORITHM, CRC32) ); AsyncSignedRequest signedRequest = signer.signAsync(request).join(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")) .hasValue("STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER"); assertThat(signedRequest.request().firstMatchingHeader(CONTENT_ENCODING)).hasValue("aws-chunked"); assertThat(signedRequest.request().firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue("314"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-decoded-content-length")).hasValue("20"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-trailer")).hasValue("x-amz-checksum-crc32"); } // TODO(sra-identity-and-auth): Replace this test with the above test once chunk-encoding support is added @Test public void signAsync_WithChunkEncodingTrueAndChecksumAlgorithm_DelegatesToAwsChunkedPayloadSigner() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader(Header.CONTENT_LENGTH, "20"), signRequest -> signRequest .putProperty(CHUNK_ENCODING_ENABLED, true) .putProperty(CHECKSUM_ALGORITHM, CRC32) ); AsyncSignedRequest signedRequest = signer.signAsync(request).join(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")) .hasValue("STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER"); assertThat(signedRequest.request().firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue("20"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-decoded-content-length")).isNotPresent(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-trailer")).isNotPresent(); } @Test public void sign_WithPayloadSigningFalseAndChunkEncodingTrueAndFlexibleChecksum_DelegatesToAwsChunkedPayloadSigner() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader(Header.CONTENT_LENGTH, "20"), signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, false) .putProperty(CHUNK_ENCODING_ENABLED, true) .putProperty(CHECKSUM_ALGORITHM, CRC32) ); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")) .hasValue("STREAMING-UNSIGNED-PAYLOAD-TRAILER"); assertThat(signedRequest.request().firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue("62"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-decoded-content-length")).hasValue("20"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-trailer")).hasValue("x-amz-checksum-crc32"); } // TODO(sra-identity-and-auth): Once chunk-encoding support in async is added, we can enable these tests. @Disabled("Chunk-encoding is not currently supported in the Async signing path - it is handled in HttpChecksumStage for now.") @Test public void signAsync_WithPayloadSigningFalseAndChunkEncodingTrueAndTrailer_DelegatesToAwsChunkedPayloadSigner_futureBehavior() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader(Header.CONTENT_LENGTH, "20"), signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, false) .putProperty(CHUNK_ENCODING_ENABLED, true) .putProperty(CHECKSUM_ALGORITHM, CRC32) ); AsyncSignedRequest signedRequest = signer.signAsync(request).join(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")) .hasValue("STREAMING-UNSIGNED-PAYLOAD-TRAILER"); assertThat(signedRequest.request().firstMatchingHeader(CONTENT_ENCODING)).hasValue("aws-chunked"); assertThat(signedRequest.request().firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue("62"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-decoded-content-length")).hasValue("20"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-trailer")).hasValue("x-amz-checksum-crc32"); } // TODO(sra-identity-and-auth): Replace this test with the above test once chunk-encoding support is added @Test public void signAsync_WithPayloadSigningFalseAndChunkEncodingTrueAndTrailer_DelegatesToAwsChunkedPayloadSigner() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader(Header.CONTENT_LENGTH, "20"), signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, false) .putProperty(CHUNK_ENCODING_ENABLED, true) .putProperty(CHECKSUM_ALGORITHM, CRC32) ); AsyncSignedRequest signedRequest = signer.signAsync(request).join(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")) .hasValue("STREAMING-UNSIGNED-PAYLOAD-TRAILER"); assertThat(signedRequest.request().firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue("20"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-decoded-content-length")).isNotPresent(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-trailer")).isNotPresent(); } @Test public void sign_WithPayloadSigningFalseAndChunkEncodingTrue_DelegatesToUnsignedPayload() { // Currently, there is no use-case for unsigned chunk-encoding without trailers, so we should assert it falls back to // unsigned-payload (not chunk-encoded) SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader(Header.CONTENT_LENGTH, "20"), signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, false) .putProperty(CHUNK_ENCODING_ENABLED, true) ); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")).hasValue("UNSIGNED-PAYLOAD"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-decoded-content-length")).isNotPresent(); } @Test public void signAsync_WithPayloadSigningFalseAndChunkEncodingTrueWithoutTrailer_DelegatesToUnsignedPayload() { // Currently, there is no use-case for unsigned chunk-encoding without trailers, so we should assert it falls back to // unsigned-payload (not chunk-encoded) AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader(Header.CONTENT_LENGTH, "20"), signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, false) .putProperty(CHUNK_ENCODING_ENABLED, true) ); AsyncSignedRequest signedRequest = signer.signAsync(request).join(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")).hasValue("UNSIGNED-PAYLOAD"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-decoded-content-length")).isNotPresent(); } @Test public void sign_WithPayloadSigningFalseAndChunkEncodingTrueWithChecksumHeader_DelegatesToUnsignedPayload() { // If a checksum is given explicitly, we shouldn't treat it as a flexible-checksum-enabled request SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader(Header.CONTENT_LENGTH, "20") .putHeader("x-amz-checksum-crc32", "bogus"), signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, false) .putProperty(CHUNK_ENCODING_ENABLED, true) ); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")).hasValue("UNSIGNED-PAYLOAD"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-checksum-crc32")).hasValue("bogus"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-decoded-content-length")).isNotPresent(); } @Test public void signAsync_WithPayloadSigningFalseAndChunkEncodingTrueWithChecksumHeader_DelegatesToUnsignedPayload() { // If a checksum is given explicitly, we shouldn't treat it as a flexible-checksum-enabled request AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader(Header.CONTENT_LENGTH, "20") .putHeader("x-amz-checksum-crc32", "bogus"), signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, false) .putProperty(CHUNK_ENCODING_ENABLED, true) ); AsyncSignedRequest signedRequest = signer.signAsync(request).join(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")).hasValue("UNSIGNED-PAYLOAD"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-checksum-crc32")).hasValue("bogus"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-decoded-content-length")).isNotPresent(); } @Test public void sign_withChecksumAlgorithm_DelegatesToChecksummerWithThatChecksumAlgorithm() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> { }, signRequest -> signRequest.putProperty(CHECKSUM_ALGORITHM, CRC32) ); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingHeader("x-amz-checksum-crc32")).isPresent(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")).isPresent(); } @Test public void signAsync_withChecksumAlgorithm_DelegatesToChecksummerWithThatChecksumAlgorithm() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> { }, signRequest -> signRequest.putProperty(CHECKSUM_ALGORITHM, CRC32) ); AsyncSignedRequest signedRequest = signer.signAsync(request).join(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-checksum-crc32")).isPresent(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")).isPresent(); } @Test public void sign_withChecksumAlgorithmAndPayloadSigningFalse_DelegatesToChecksummerWithThatChecksumAlgorithm() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> { }, signRequest -> signRequest .putProperty(CHECKSUM_ALGORITHM, CRC32) .putProperty(PAYLOAD_SIGNING_ENABLED, false) ); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingHeader("x-amz-checksum-crc32")).isPresent(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")).hasValue("UNSIGNED-PAYLOAD"); } @Test public void signAsync_withChecksumAlgorithmAndPayloadSigningFalse_DelegatesToChecksummerWithThatChecksumAlgorithm() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> { }, signRequest -> signRequest .putProperty(CHECKSUM_ALGORITHM, CRC32) .putProperty(PAYLOAD_SIGNING_ENABLED, false) ); AsyncSignedRequest signedRequest = signer.signAsync(request).join(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-checksum-crc32")).isPresent(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")).hasValue("UNSIGNED-PAYLOAD"); } @Test public void sign_WithPayloadSigningFalseAndHttp_FallsBackToPayloadSigning() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest.uri(URI.create("http://demo.us-east-1.amazonaws.com")), signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, false) ); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")) .hasValue("a15c8292b1d12abbbbe4148605f7872fbdf645618fee5ab0e8072a7b34f155e2"); } @Test public void signAsync_WithPayloadSigningFalseAndHttp_FallsBackToPayloadSigning() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest.uri(URI.create("http://demo.us-east-1.amazonaws.com")), signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, false) ); AsyncSignedRequest signedRequest = signer.signAsync(request).join(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")) .hasValue("a15c8292b1d12abbbbe4148605f7872fbdf645618fee5ab0e8072a7b34f155e2"); } @Test public void sign_WithPayloadSigningTrueAndChunkEncodingTrueAndHttp_SignsPayload() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest.uri(URI.create("http://demo.us-east-1.amazonaws.com")), signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, true) .putProperty(CHUNK_ENCODING_ENABLED, true) ); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")) .hasValue("STREAMING-AWS4-HMAC-SHA256-PAYLOAD"); assertThat(signedRequest.request().firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue("193"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-decoded-content-length")).hasValue("20"); } // TODO(sra-identity-and-auth): Once chunk-encoding is implemented in the async path, the assertions this test makes should // be different - the assertions should mirror the above case. @Test public void signAsync_WithPayloadSigningTrueAndChunkEncodingTrueAndHttp_IgnoresPayloadSigning() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest.uri(URI.create("http://demo.us-east-1.amazonaws.com")), signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, true) .putProperty(CHUNK_ENCODING_ENABLED, true) ); AsyncSignedRequest signedRequest = signer.signAsync(request).join(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")) .hasValue("UNSIGNED-PAYLOAD"); } @Test public void sign_WithPayloadSigningFalseAndChunkEncodingTrueAndHttp_SignsPayload() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest.uri(URI.create("http://demo.us-east-1.amazonaws.com")), signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, false) .putProperty(CHUNK_ENCODING_ENABLED, true) ); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")) .hasValue("STREAMING-AWS4-HMAC-SHA256-PAYLOAD"); assertThat(signedRequest.request().firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue("193"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-decoded-content-length")).hasValue("20"); } // TODO(sra-identity-and-auth): Once chunk-encoding is implemented in the async path, the assertions this test makes should // be different - the assertions should mirror the above case. @Test public void signAsync_WithPayloadSigningFalseAndChunkEncodingTrueAndHttp_DoesNotFallBackToPayloadSigning() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest.uri(URI.create("http://demo.us-east-1.amazonaws.com")), signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, false) .putProperty(CHUNK_ENCODING_ENABLED, true) ); AsyncSignedRequest signedRequest = signer.signAsync(request).join(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")) .hasValue("UNSIGNED-PAYLOAD"); } @Test public void sign_WithPayloadSigningFalseAndChunkEncodingTrueAndFlexibleChecksumAndHttp_SignsPayload() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest.uri(URI.create("http://demo.us-east-1.amazonaws.com")), signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, false) .putProperty(CHUNK_ENCODING_ENABLED, true) .putProperty(CHECKSUM_ALGORITHM, CRC32) ); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")) .hasValue("STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER"); assertThat(signedRequest.request().firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue("314"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-decoded-content-length")).hasValue("20"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-trailer")).hasValue("x-amz-checksum-crc32"); } // TODO(sra-identity-and-auth): Once chunk-encoding is implemented in the async path, the assertions this test makes should // be different - the assertions should mirror the above case. @Test public void signAsync_WithPayloadSigningFalseAndChunkEncodingTrueAndFlexibleChecksumAndHttp_DoesNotFallBackToPayloadSigning() { AsyncSignRequest<? extends AwsCredentialsIdentity> request = generateBasicAsyncRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest.uri(URI.create("http://demo.us-east-1.amazonaws.com")), signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, false) .putProperty(CHUNK_ENCODING_ENABLED, true) .putProperty(CHECKSUM_ALGORITHM, CRC32) ); AsyncSignedRequest signedRequest = signer.signAsync(request).join(); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")) .hasValue("STREAMING-UNSIGNED-PAYLOAD-TRAILER"); } }
2,549
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer/RollingSignerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.signer; import static org.junit.jupiter.api.Assertions.assertEquals; import java.nio.charset.StandardCharsets; import org.junit.jupiter.api.Test; public class RollingSignerTest { @Test public void sign_shouldRollSignature() { RollingSigner signer = new RollingSigner("key".getBytes(StandardCharsets.UTF_8), "seed"); String first = signer.sign(signature -> signature + "a"); String second = signer.sign(signature -> signature + "b"); String third = signer.sign(signature -> signature + "c"); assertEquals("878b44846ec83a43c3932578c5311fa8b289ae194ccc0c06244c366f3b949012", first); assertEquals("08f47cc56d186cee34fa7662128d5c9187eb9483938df45282e922d902e85a27", second); assertEquals("10da3ca4a393be5f8368823cb73a777426db24428bd8374fbf54a64a808ff00a", third); } @Test public void reset_shouldResetSeed() { RollingSigner signer = new RollingSigner("key".getBytes(StandardCharsets.UTF_8), "seed"); String first = signer.sign(signature -> signature + "a"); String second = signer.sign(signature -> signature + "b"); signer.reset(); String firstAgain = signer.sign(signature -> signature + "a"); assertEquals("878b44846ec83a43c3932578c5311fa8b289ae194ccc0c06244c366f3b949012", first); assertEquals("08f47cc56d186cee34fa7662128d5c9187eb9483938df45282e922d902e85a27", second); assertEquals("878b44846ec83a43c3932578c5311fa8b289ae194ccc0c06244c366f3b949012", firstAgain); } }
2,550
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer/V4CanonicalRequestTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.signer; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Arrays; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.utils.ToString; /** * Tests how canonical resource paths are created including normalization */ public class V4CanonicalRequestTest { public static Iterable<TestCase> data() { return Arrays.asList( // Handling slash tc("Empty path -> (initial) slash added", "", "/"), tc("Slash -> unchanged", "/", "/"), tc("Single segment with initial slash -> unchanged", "/foo", "/foo"), tc("Single segment no slash -> slash prepended", "foo", "/foo"), tc("Multiple segments -> unchanged", "/foo/bar", "/foo/bar"), tc("Multiple segments with trailing slash -> unchanged", "/foo/bar/", "/foo/bar/"), // Double URL encoding tc("Multiple segments, urlEncoded slash -> encodes percent", "/foo%2Fbar", "/foo%252Fbar", true, true), // No double-url-encoding + normalization tc("Single segment, dot -> should remove dot", "/.", "/"), tc("Single segment, double dot -> unchanged", "/..", "/.."), tc("Multiple segments with dot -> should remove dot", "/foo/./bar", "/foo/bar"), tc("Multiple segments with ending dot -> should remove dot and trailing slash", "/foo/bar/.", "/foo/bar"), tc("Multiple segments with dots -> should remove dots and preceding segment", "/foo/bar/../baz", "/foo/baz"), tc("First segment has colon -> unchanged, url encoded first", "foo:/bar", "/foo%3A/bar", true, true), // Double-url-encoding + normalization tc("Multiple segments, urlEncoded slash -> encodes percent", "/foo%2F.%2Fbar", "/foo%252F.%252Fbar", true, true), // Double-url-encoding + no normalization tc("No url encode, Multiple segments with dot -> unchanged", "/foo/./bar", "/foo/./bar", false, false), tc("Multiple segments with dots -> unchanged", "/foo/bar/../baz", "/foo/bar/../baz", false, false) ); } private static TestCase tc(String name, String path, String expectedPath) { return new TestCase(name, path, expectedPath, false, true); } private static TestCase tc(String name, String path, String expectedPath, boolean urlEncode, boolean normalizePath) { return new TestCase(name, path, expectedPath, urlEncode, normalizePath); } @ParameterizedTest @MethodSource("data") public void verifyNormalizedPath(TestCase tc) { String canonicalRequest = tc.canonicalRequest.getCanonicalRequestString(); String[] requestParts = canonicalRequest.split("\\n"); String canonicalPath = requestParts[1]; assertEquals(tc.expectedPath, canonicalPath); } @Test public void canonicalRequest_WithForbiddenHeaders_shouldExcludeForbidden() { SdkHttpRequest request = SdkHttpRequest.builder() .protocol("https") .host("localhost") .method(SdkHttpMethod.PUT) .putHeader("foo", "bar") .putHeader("x-amzn-trace-id", "wontBePresent") .build(); V4CanonicalRequest cr = new V4CanonicalRequest(request, "sha-256", new V4CanonicalRequest.Options(true, true)); assertEquals("PUT\n/\n\nfoo:bar\n\nfoo\nsha-256", cr.getCanonicalRequestString()); } @Test public void canonicalRequest_WithMultiValueHeaders_shouldCommaSeparateValues() { SdkHttpRequest request = SdkHttpRequest.builder() .protocol("https") .host("localhost") .method(SdkHttpMethod.PUT) .appendHeader("foo", "bar") .appendHeader("foo", "baz") .build(); V4CanonicalRequest cr = new V4CanonicalRequest(request, "sha-256", new V4CanonicalRequest.Options(true, true)); assertEquals("PUT\n/\n\nfoo:bar,baz\n\nfoo\nsha-256", cr.getCanonicalRequestString()); } @Test public void canonicalRequest_withSpacedHeaders_shouldStripWhitespace() { SdkHttpRequest request = SdkHttpRequest.builder() .protocol("https") .host("localhost") .method(SdkHttpMethod.PUT) .putHeader("foo", " bar baz ") .build(); V4CanonicalRequest cr = new V4CanonicalRequest(request, "sha-256", new V4CanonicalRequest.Options(true, true)); assertEquals("PUT\n/\n\nfoo:bar baz\n\nfoo\nsha-256", cr.getCanonicalRequestString()); } @Test public void canonicalRequest_WithNullParamValue_shouldIncludeEquals() { SdkHttpRequest request = SdkHttpRequest.builder() .protocol("https") .host("localhost") .method(SdkHttpMethod.PUT) .putRawQueryParameter("foo", (String) null) .build(); V4CanonicalRequest cr = new V4CanonicalRequest(request, "sha-256", new V4CanonicalRequest.Options(true, true)); assertEquals("PUT\n/\nfoo=\n\n\nsha-256", cr.getCanonicalRequestString()); } @Test public void canonicalRequest_WithEmptyParamKey_shouldExcludeParam() { SdkHttpRequest request = SdkHttpRequest.builder() .protocol("https") .host("localhost") .method(SdkHttpMethod.PUT) .putRawQueryParameter("", "") .build(); V4CanonicalRequest cr = new V4CanonicalRequest(request, "sha-256", new V4CanonicalRequest.Options(true, true)); assertEquals("PUT\n/\n\n\n\nsha-256", cr.getCanonicalRequestString()); } private static class TestCase { private final String name; private final String path; private final String expectedPath; private final V4CanonicalRequest canonicalRequest; private TestCase(String name, String path, String expectedPath, boolean doubleUrlEncode, boolean normalizePath) { SdkHttpRequest request = SdkHttpRequest.builder() .protocol("https") .host("localhost") .encodedPath(path) .method(SdkHttpMethod.PUT) .build(); this.name = name; this.path = path; this.expectedPath = expectedPath; this.canonicalRequest = new V4CanonicalRequest(request, "sha-256", new V4CanonicalRequest.Options(doubleUrlEncode, normalizePath)); } @Override public String toString() { return ToString.builder("TestCase") .add("name", name) .add("path", path) .add("expectedPath", expectedPath) .build(); } } }
2,551
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer/AwsChunkedV4PayloadSignerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.signer; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static software.amazon.awssdk.checksums.DefaultChecksumAlgorithm.CRC32; import static software.amazon.awssdk.checksums.DefaultChecksumAlgorithm.SHA256; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.nio.charset.StandardCharsets; import java.time.Instant; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.http.ContentStreamProvider; import software.amazon.awssdk.http.Header; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; /** * Test the delegation of signing to the correct implementations. */ public class AwsChunkedV4PayloadSignerTest { int chunkSize = 4; CredentialScope credentialScope = new CredentialScope("us-east-1", "s3", Instant.EPOCH); byte[] data = "{\"TableName\": \"foo\"}".getBytes(); ContentStreamProvider payload = () -> new ByteArrayInputStream(data); SdkHttpRequest.Builder requestBuilder; @BeforeEach public void setUp() { requestBuilder = SdkHttpRequest .builder() .method(SdkHttpMethod.POST) .putHeader("Host", "demo.us-east-1.amazonaws.com") .putHeader("x-amz-archive-description", "test test") .putHeader(Header.CONTENT_LENGTH, Integer.toString(data.length)) .encodedPath("/") .uri(URI.create("http://demo.us-east-1.amazonaws.com")); } @Test public void sign_withSignedPayload_shouldChunkEncodeWithSigV4Ext() throws IOException { String expectedContent = "4;chunk-signature=082f5b0e588893570e152b401a886161ee772ed066948f68c8f01aee11cca4f8\r\n{\"Ta\r\n" + "4;chunk-signature=777b02ec61ce7934578b1efe6fbe08c21ae4a8cdf66a709d3b4fd320dddd2839\r\nbleN\r\n" + "4;chunk-signature=84abdae650f64dee4d703d41c7d87c8bc251c22b8c493c75ce24431b60b73937\r\name\"\r\n" + "4;chunk-signature=aff22ddad9d4388233fe9bc47e9c552a6e9ba9285af79555d2ce7fdaab726320\r\n: \"f\r\n" + "4;chunk-signature=30e55f4e1c1fd444c06e9be42d9594b8fd7ead436bc67a58b5350ffd58b6aaa5\r\noo\"}\r\n" + "0;chunk-signature=825ad80195cae47f54984835543ff2179c2c5a53c324059cd632e50259384ee3\r\n\r\n"; requestBuilder.putHeader("x-amz-content-sha256", "STREAMING-AWS4-HMAC-SHA256-PAYLOAD"); V4CanonicalRequest canonicalRequest = new V4CanonicalRequest( requestBuilder.build(), "STREAMING-AWS4-HMAC-SHA256-PAYLOAD", new V4CanonicalRequest.Options(true, true) ); V4RequestSigningResult requestSigningResult = new V4RequestSigningResult( "STREAMING-AWS4-HMAC-SHA256-PAYLOAD", "key".getBytes(StandardCharsets.UTF_8), "sig", canonicalRequest, requestBuilder ); AwsChunkedV4PayloadSigner signer = AwsChunkedV4PayloadSigner.builder() .credentialScope(credentialScope) .chunkSize(chunkSize) .build(); signer.beforeSigning(requestBuilder, null); ContentStreamProvider signedPayload = signer.sign(payload, requestSigningResult); assertThat(requestBuilder.firstMatchingHeader("x-amz-decoded-content-length")).hasValue(Integer.toString(data.length)); byte[] tmp = new byte[1024]; int actualBytes = readAll(signedPayload.newStream(), tmp); assertThat(requestBuilder.firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue(Integer.toString(actualBytes)); assertEquals(expectedContent, new String(tmp, 0, actualBytes)); } @Test public void sign_withSignedPayloadAndChecksum_shouldChunkEncodeWithSigV4ExtAndSigV4Trailer() throws IOException { String expectedContent = "4;chunk-signature=082f5b0e588893570e152b401a886161ee772ed066948f68c8f01aee11cca4f8\r\n{\"Ta\r\n" + "4;chunk-signature=777b02ec61ce7934578b1efe6fbe08c21ae4a8cdf66a709d3b4fd320dddd2839\r\nbleN\r\n" + "4;chunk-signature=84abdae650f64dee4d703d41c7d87c8bc251c22b8c493c75ce24431b60b73937\r\name\"\r\n" + "4;chunk-signature=aff22ddad9d4388233fe9bc47e9c552a6e9ba9285af79555d2ce7fdaab726320\r\n: \"f\r\n" + "4;chunk-signature=30e55f4e1c1fd444c06e9be42d9594b8fd7ead436bc67a58b5350ffd58b6aaa5\r\noo\"}\r\n" + "0;chunk-signature=825ad80195cae47f54984835543ff2179c2c5a53c324059cd632e50259384ee3\r\n" + "x-amz-checksum-crc32:oL+a/g==\r\n" + "x-amz-trailer-signature:23457d04f4a8e279780cb91e28d4fbd1c6a2dd678d419705461a80514cea206c\r\n\r\n"; requestBuilder.putHeader("x-amz-content-sha256", "STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER"); V4CanonicalRequest canonicalRequest = new V4CanonicalRequest( requestBuilder.build(), "STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER", new V4CanonicalRequest.Options(true, true) ); V4RequestSigningResult requestSigningResult = new V4RequestSigningResult( "STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER", "key".getBytes(StandardCharsets.UTF_8), "sig", canonicalRequest, requestBuilder ); AwsChunkedV4PayloadSigner signer = AwsChunkedV4PayloadSigner.builder() .credentialScope(credentialScope) .chunkSize(chunkSize) .checksumAlgorithm(CRC32) .build(); signer.beforeSigning(requestBuilder, payload); ContentStreamProvider signedPayload = signer.sign(payload, requestSigningResult); assertThat(requestBuilder.firstMatchingHeader("x-amz-decoded-content-length")).hasValue(Integer.toString(data.length)); assertThat(requestBuilder.firstMatchingHeader("x-amz-trailer")).hasValue("x-amz-checksum-crc32"); byte[] tmp = new byte[1024]; int actualBytes = readAll(signedPayload.newStream(), tmp); assertThat(requestBuilder.firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue(Integer.toString(actualBytes)); assertEquals(expectedContent, new String(tmp, 0, actualBytes)); } @Test public void sign_withChecksum_shouldChunkEncodeWithChecksumTrailer() throws IOException { String expectedContent = "4\r\n{\"Ta\r\n" + "4\r\nbleN\r\n" + "4\r\name\"\r\n" + "4\r\n: \"f\r\n" + "4\r\noo\"}\r\n" + "0\r\n" + "x-amz-checksum-sha256:oVyCkrHRKru75BSGBfeHL732RWGP7lqw6AcqezTxVeI=\r\n\r\n"; requestBuilder.putHeader("x-amz-content-sha256", "STREAMING-UNSIGNED-PAYLOAD-TRAILER"); V4CanonicalRequest canonicalRequest = new V4CanonicalRequest( requestBuilder.build(), "STREAMING-UNSIGNED-PAYLOAD-TRAILER", new V4CanonicalRequest.Options(true, true) ); V4RequestSigningResult requestSigningResult = new V4RequestSigningResult( "STREAMING-UNSIGNED-PAYLOAD-TRAILER", "key".getBytes(StandardCharsets.UTF_8), "sig", canonicalRequest, requestBuilder ); AwsChunkedV4PayloadSigner signer = AwsChunkedV4PayloadSigner.builder() .credentialScope(credentialScope) .chunkSize(chunkSize) .checksumAlgorithm(SHA256) .build(); signer.beforeSigning(requestBuilder, payload); ContentStreamProvider signedPayload = signer.sign(payload, requestSigningResult); assertThat(requestBuilder.firstMatchingHeader("x-amz-decoded-content-length")).hasValue(Integer.toString(data.length)); assertThat(requestBuilder.firstMatchingHeader("x-amz-trailer")).hasValue("x-amz-checksum-sha256"); byte[] tmp = new byte[1024]; int actualBytes = readAll(signedPayload.newStream(), tmp); assertThat(requestBuilder.firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue(Integer.toString(actualBytes)); assertEquals(expectedContent, new String(tmp, 0, actualBytes)); } @Test public void sign_withPreExistingTrailers_shouldChunkEncodeWithExistingTrailers() throws IOException { String expectedContent = "4\r\n{\"Ta\r\n" + "4\r\nbleN\r\n" + "4\r\name\"\r\n" + "4\r\n: \"f\r\n" + "4\r\noo\"}\r\n" + "0\r\n" + "PreExistingHeader1:someValue1,someValue2\r\n" + "PreExistingHeader2:someValue3\r\n\r\n"; requestBuilder .putHeader("x-amz-content-sha256", "STREAMING-UNSIGNED-PAYLOAD-TRAILER") .appendHeader("PreExistingHeader1", "someValue1") .appendHeader("PreExistingHeader1", "someValue2") .appendHeader("PreExistingHeader2", "someValue3") .appendHeader("x-amz-trailer", "PreExistingHeader1") .appendHeader("x-amz-trailer", "PreExistingHeader2"); V4CanonicalRequest canonicalRequest = new V4CanonicalRequest( requestBuilder.build(), "STREAMING-UNSIGNED-PAYLOAD-TRAILER", new V4CanonicalRequest.Options(true, true) ); V4RequestSigningResult requestSigningResult = new V4RequestSigningResult( "STREAMING-UNSIGNED-PAYLOAD-TRAILER", "key".getBytes(StandardCharsets.UTF_8), "sig", canonicalRequest, requestBuilder ); AwsChunkedV4PayloadSigner signer = AwsChunkedV4PayloadSigner.builder() .credentialScope(credentialScope) .chunkSize(chunkSize) .build(); signer.beforeSigning(requestBuilder, payload); ContentStreamProvider signedPayload = signer.sign(payload, requestSigningResult); assertThat(requestBuilder.firstMatchingHeader("x-amz-decoded-content-length")).hasValue(Integer.toString(data.length)); assertThat(requestBuilder.firstMatchingHeader("PreExistingHeader1")).isNotPresent(); assertThat(requestBuilder.firstMatchingHeader("PreExistingHeader2")).isNotPresent(); assertThat(requestBuilder.matchingHeaders("x-amz-trailer")).contains("PreExistingHeader1", "PreExistingHeader2"); byte[] tmp = new byte[1024]; int actualBytes = readAll(signedPayload.newStream(), tmp); assertThat(requestBuilder.firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue(Integer.toString(actualBytes)); assertEquals(expectedContent, new String(tmp, 0, actualBytes)); } @Test public void sign_withPreExistingTrailersAndChecksum_shouldChunkEncodeWithTrailers() throws IOException { String expectedContent = "4\r\n{\"Ta\r\n" + "4\r\nbleN\r\n" + "4\r\name\"\r\n" + "4\r\n: \"f\r\n" + "4\r\noo\"}\r\n" + "0\r\n" + "PreExistingHeader1:someValue1,someValue2\r\n" + "PreExistingHeader2:someValue3\r\n" + "x-amz-checksum-crc32:oL+a/g==\r\n\r\n"; requestBuilder .putHeader("x-amz-content-sha256", "STREAMING-UNSIGNED-PAYLOAD-TRAILER") .appendHeader("PreExistingHeader1", "someValue1") .appendHeader("PreExistingHeader1", "someValue2") .appendHeader("PreExistingHeader2", "someValue3") .appendHeader("x-amz-trailer", "PreExistingHeader1") .appendHeader("x-amz-trailer", "PreExistingHeader2"); V4CanonicalRequest canonicalRequest = new V4CanonicalRequest( requestBuilder.build(), "STREAMING-UNSIGNED-PAYLOAD-TRAILER", new V4CanonicalRequest.Options(true, true) ); V4RequestSigningResult requestSigningResult = new V4RequestSigningResult( "STREAMING-UNSIGNED-PAYLOAD-TRAILER", "key".getBytes(StandardCharsets.UTF_8), "sig", canonicalRequest, requestBuilder ); AwsChunkedV4PayloadSigner signer = AwsChunkedV4PayloadSigner.builder() .credentialScope(credentialScope) .chunkSize(chunkSize) .checksumAlgorithm(CRC32) .build(); signer.beforeSigning(requestBuilder, payload); ContentStreamProvider signedPayload = signer.sign(payload, requestSigningResult); assertThat(requestBuilder.firstMatchingHeader("x-amz-decoded-content-length")).hasValue(Integer.toString(data.length)); assertThat(requestBuilder.firstMatchingHeader("PreExistingHeader1")).isNotPresent(); assertThat(requestBuilder.firstMatchingHeader("PreExistingHeader2")).isNotPresent(); assertThat(requestBuilder.matchingHeaders("x-amz-trailer")).contains( "PreExistingHeader1", "PreExistingHeader2", "x-amz-checksum-crc32" ); byte[] tmp = new byte[1024]; int actualBytes = readAll(signedPayload.newStream(), tmp); assertThat(requestBuilder.firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue(Integer.toString(actualBytes)); assertEquals(expectedContent, new String(tmp, 0, actualBytes)); } @Test public void sign_withPreExistingTrailersAndChecksumAndSignedPayload_shouldAwsChunkEncode() throws IOException { String expectedContent = "4;chunk-signature=082f5b0e588893570e152b401a886161ee772ed066948f68c8f01aee11cca4f8\r\n{\"Ta\r\n" + "4;chunk-signature=777b02ec61ce7934578b1efe6fbe08c21ae4a8cdf66a709d3b4fd320dddd2839\r\nbleN\r\n" + "4;chunk-signature=84abdae650f64dee4d703d41c7d87c8bc251c22b8c493c75ce24431b60b73937\r\name\"\r\n" + "4;chunk-signature=aff22ddad9d4388233fe9bc47e9c552a6e9ba9285af79555d2ce7fdaab726320\r\n: \"f\r\n" + "4;chunk-signature=30e55f4e1c1fd444c06e9be42d9594b8fd7ead436bc67a58b5350ffd58b6aaa5\r\noo\"}\r\n" + "0;chunk-signature=825ad80195cae47f54984835543ff2179c2c5a53c324059cd632e50259384ee3\r\n" + "zzz:123\r\n" + "PreExistingHeader1:someValue1\r\n" + "x-amz-checksum-crc32:oL+a/g==\r\n" + "x-amz-trailer-signature:3f65ab57ede6a5fb7c77b14b35faf2d9dd2c6d89828bdae189a04f3677bc16f2\r\n\r\n"; requestBuilder .putHeader("x-amz-content-sha256", "STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER") .appendHeader("PreExistingHeader1", "someValue1") .appendHeader("zzz", "123") .appendHeader("x-amz-trailer", "zzz") .appendHeader("x-amz-trailer", "PreExistingHeader1"); V4CanonicalRequest canonicalRequest = new V4CanonicalRequest( requestBuilder.build(), "STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER", new V4CanonicalRequest.Options(true, true) ); V4RequestSigningResult requestSigningResult = new V4RequestSigningResult( "STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER", "key".getBytes(StandardCharsets.UTF_8), "sig", canonicalRequest, requestBuilder ); AwsChunkedV4PayloadSigner signer = AwsChunkedV4PayloadSigner.builder() .credentialScope(credentialScope) .chunkSize(chunkSize) .checksumAlgorithm(CRC32) .build(); signer.beforeSigning(requestBuilder, payload); ContentStreamProvider signedPayload = signer.sign(payload, requestSigningResult); assertThat(requestBuilder.firstMatchingHeader("x-amz-decoded-content-length")).hasValue(Integer.toString(data.length)); assertThat(requestBuilder.firstMatchingHeader("PreExistingHeader1")).isNotPresent(); assertThat(requestBuilder.matchingHeaders("x-amz-trailer")).contains("zzz", "PreExistingHeader1", "x-amz-checksum-crc32"); byte[] tmp = new byte[1024]; int actualBytes = readAll(signedPayload.newStream(), tmp); assertThat(requestBuilder.firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue(Integer.toString(actualBytes)); assertEquals(expectedContent, new String(tmp, 0, actualBytes)); } @Test public void sign_withoutContentLength_calculatesContentLengthFromPayload() throws IOException { String expectedContent = "4\r\n{\"Ta\r\n" + "4\r\nbleN\r\n" + "4\r\name\"\r\n" + "4\r\n: \"f\r\n" + "4\r\noo\"}\r\n" + "0\r\n" + "x-amz-checksum-sha256:oVyCkrHRKru75BSGBfeHL732RWGP7lqw6AcqezTxVeI=\r\n\r\n"; requestBuilder.putHeader("x-amz-content-sha256", "STREAMING-UNSIGNED-PAYLOAD-TRAILER"); requestBuilder.removeHeader(Header.CONTENT_LENGTH); V4CanonicalRequest canonicalRequest = new V4CanonicalRequest( requestBuilder.build(), "STREAMING-UNSIGNED-PAYLOAD-TRAILER", new V4CanonicalRequest.Options(true, true) ); V4RequestSigningResult requestSigningResult = new V4RequestSigningResult( "STREAMING-UNSIGNED-PAYLOAD-TRAILER", "key".getBytes(StandardCharsets.UTF_8), "sig", canonicalRequest, requestBuilder ); AwsChunkedV4PayloadSigner signer = AwsChunkedV4PayloadSigner.builder() .credentialScope(credentialScope) .chunkSize(chunkSize) .checksumAlgorithm(SHA256) .build(); signer.beforeSigning(requestBuilder, payload); ContentStreamProvider signedPayload = signer.sign(payload, requestSigningResult); assertThat(requestBuilder.firstMatchingHeader("x-amz-decoded-content-length")).hasValue(Integer.toString(data.length)); assertThat(requestBuilder.firstMatchingHeader("x-amz-trailer")).hasValue("x-amz-checksum-sha256"); byte[] tmp = new byte[1024]; int actualBytes = readAll(signedPayload.newStream(), tmp); assertThat(requestBuilder.firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue(Integer.toString(actualBytes)); assertEquals(expectedContent, new String(tmp, 0, actualBytes)); } @Test public void sign_shouldReturnResettableContentStreamProvider() throws IOException { String expectedContent = "4;chunk-signature=082f5b0e588893570e152b401a886161ee772ed066948f68c8f01aee11cca4f8\r\n{\"Ta\r\n" + "4;chunk-signature=777b02ec61ce7934578b1efe6fbe08c21ae4a8cdf66a709d3b4fd320dddd2839\r\nbleN\r\n" + "4;chunk-signature=84abdae650f64dee4d703d41c7d87c8bc251c22b8c493c75ce24431b60b73937\r\name\"\r\n" + "4;chunk-signature=aff22ddad9d4388233fe9bc47e9c552a6e9ba9285af79555d2ce7fdaab726320\r\n: \"f\r\n" + "4;chunk-signature=30e55f4e1c1fd444c06e9be42d9594b8fd7ead436bc67a58b5350ffd58b6aaa5\r\noo\"}\r\n" + "0;chunk-signature=825ad80195cae47f54984835543ff2179c2c5a53c324059cd632e50259384ee3\r\n\r\n"; requestBuilder.putHeader("x-amz-content-sha256", "STREAMING-AWS4-HMAC-SHA256-PAYLOAD"); V4CanonicalRequest canonicalRequest = new V4CanonicalRequest( requestBuilder.build(), "STREAMING-AWS4-HMAC-SHA256-PAYLOAD", new V4CanonicalRequest.Options(true, true) ); V4RequestSigningResult requestSigningResult = new V4RequestSigningResult( "STREAMING-AWS4-HMAC-SHA256-PAYLOAD", "key".getBytes(StandardCharsets.UTF_8), "sig", canonicalRequest, requestBuilder ); AwsChunkedV4PayloadSigner signer = AwsChunkedV4PayloadSigner.builder() .credentialScope(credentialScope) .chunkSize(chunkSize) .build(); signer.beforeSigning(requestBuilder, payload); ContentStreamProvider signedPayload = signer.sign(payload, requestSigningResult); // successive calls to newStream() should return a stream with the same data every time - this makes sure that state // isn't carried over to the new streams returned by newStream() byte[] tmp = new byte[1024]; for (int i = 0; i < 2; i++) { int actualBytes = readAll(signedPayload.newStream(), tmp); assertEquals(expectedContent, new String(tmp, 0, actualBytes)); } } @Test public void signAsync_throws() { AwsChunkedV4PayloadSigner signer = AwsChunkedV4PayloadSigner.builder() .credentialScope(credentialScope) .chunkSize(chunkSize) .build(); assertThrows(UnsupportedOperationException.class, () -> signer.signAsync(null, null)); } private int readAll(InputStream src, byte[] dst) throws IOException { int read = 0; int offset = 0; while (read >= 0) { read = src.read(); if (read >= 0) { dst[offset] = (byte) read; offset += 1; } } return offset; } }
2,552
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer/V4RequestSignerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.signer; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static software.amazon.awssdk.http.auth.aws.TestUtils.TickingClock; import static software.amazon.awssdk.http.auth.aws.internal.signer.V4RequestSigner.header; import static software.amazon.awssdk.http.auth.aws.internal.signer.V4RequestSigner.presigned; import static software.amazon.awssdk.http.auth.aws.internal.signer.V4RequestSigner.query; import java.net.URI; import java.time.Clock; import java.time.Duration; import java.time.Instant; import org.junit.jupiter.api.Test; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.AwsSessionCredentialsIdentity; public class V4RequestSignerTest { private static final AwsCredentialsIdentity creds = AwsCredentialsIdentity.create("access", "secret"); private static final AwsSessionCredentialsIdentity sessionCreds = AwsSessionCredentialsIdentity.create("access", "secret", "token"); @Test public void sign_computesSigningResult() { String expectedSignature = "4c7049543386ba32bc85e7a7d7b892e7da1c412abf3508ca84775ed099790acf"; String expectedContentHash = "abc123"; String expectedCanonicalRequestString = "GET\n" + "/./foo\n\n" + "x-amz-archive-description:test test\n" + "x-amz-content-sha256:checksum\n\n" + "x-amz-archive-description;x-amz-content-sha256\n" + "abc123"; V4RequestSigningResult result = V4RequestSigner.create(getProperties(creds), "abc123").sign(getRequest()); assertEquals(expectedSignature, result.getSignature()); assertEquals(expectedContentHash, result.getContentHash()); assertEquals(expectedCanonicalRequestString, result.getCanonicalRequest().getCanonicalRequestString()); } @Test public void sign_withHeader_addsAuthHeaders() { String expectedAuthorization = "AWS4-HMAC-SHA256 Credential=access/19700101/us-east-1/demo/aws4_request, " + "SignedHeaders=host;x-amz-archive-description;x-amz-content-sha256;x-amz-date, " + "Signature=0fafd04465eb6201e868a80f72d15d50731512298f554684ce6627c0619f429a"; V4RequestSigningResult result = header(getProperties(creds)).sign(getRequest()); assertThat(result.getSignedRequest().firstMatchingHeader("X-Amz-Date")).hasValue("19700101T000000Z"); assertThat(result.getSignedRequest().firstMatchingHeader("Authorization")).hasValue(expectedAuthorization); } @Test public void sign_withHeaderAndSessionCredentials_addsAuthHeadersAndTokenHeader() { String expectedAuthorization = "AWS4-HMAC-SHA256 Credential=access/19700101/us-east-1/demo/aws4_request, " + "SignedHeaders=host;x-amz-archive-description;x-amz-content-sha256;x-amz-date;" + "x-amz-security-token, " + "Signature=cda79272f6d258c2cb2f04ac84a5f9515440e0158bf39e212c3dcf88b3a477a9"; V4RequestSigningResult result = header(getProperties(sessionCreds)).sign(getRequest()); assertThat(result.getSignedRequest().firstMatchingHeader("X-Amz-Date")).hasValue("19700101T000000Z"); assertThat(result.getSignedRequest().firstMatchingHeader("Authorization")).hasValue(expectedAuthorization); assertThat(result.getSignedRequest().firstMatchingHeader("X-Amz-Security-Token")).hasValue("token"); } @Test public void sign_withQuery_addsAuthQueryParams() { V4RequestSigningResult result = query(getProperties(creds)).sign(getRequest()); assertEquals("AWS4-HMAC-SHA256", result.getSignedRequest().rawQueryParameters().get("X-Amz-Algorithm").get(0)); assertEquals("19700101T000000Z", result.getSignedRequest().rawQueryParameters().get("X-Amz-Date").get(0)); assertEquals("host;x-amz-archive-description;x-amz-content-sha256", result.getSignedRequest().rawQueryParameters().get("X-Amz-SignedHeaders").get(0)); assertEquals("access/19700101/us-east-1/demo/aws4_request", result.getSignedRequest().rawQueryParameters().get( "X-Amz-Credential").get(0)); assertEquals("bb3ddb98bc32b85c8aa484bfaf321171a22ad802baa03ee9d5fcda9842b769c9", result.getSignedRequest().rawQueryParameters().get("X-Amz-Signature").get(0)); } @Test public void sign_withQueryAndSessionCredentials_addsAuthQueryParamsAndTokenParam() { V4RequestSigningResult result = query(getProperties(sessionCreds)).sign(getRequest()); assertEquals("AWS4-HMAC-SHA256", result.getSignedRequest().rawQueryParameters().get("X-Amz-Algorithm").get(0)); assertEquals("19700101T000000Z", result.getSignedRequest().rawQueryParameters().get("X-Amz-Date").get(0)); assertEquals("host;x-amz-archive-description;x-amz-content-sha256", result.getSignedRequest().rawQueryParameters().get("X-Amz-SignedHeaders").get(0)); assertEquals( "access/19700101/us-east-1/demo/aws4_request", result.getSignedRequest().rawQueryParameters().get("X-Amz-Credential").get(0)); assertEquals("2ffe9562fefd57e14f43bf1937b6b85cc0f0180d63789254bddec25498e14a29", result.getSignedRequest().rawQueryParameters().get("X-Amz-Signature").get(0)); assertEquals("token", result.getSignedRequest().rawQueryParameters().get("X-Amz-Security-Token").get(0)); } @Test public void sign_withPresigned_addsExpirationParam() { V4RequestSigningResult result = presigned(getProperties(creds), Duration.ZERO).sign(getRequest()); assertEquals("0", result.getSignedRequest().rawQueryParameters().get("X-Amz-Expires").get(0)); assertEquals("host;x-amz-archive-description", result.getSignedRequest().rawQueryParameters().get("X-Amz-SignedHeaders").get(0)); assertEquals("691f39caa2064fe4fb897976dfb4b09df54749c825a5fcd1e2f0b3fcd1bcc600", result.getSignature()); } @Test public void sign_withHeader_withNoContentHashHeader_throws() { SdkHttpRequest.Builder request = getRequest().removeHeader("x-amz-content-sha256"); assertThrows(IllegalArgumentException.class, () -> header(getProperties(sessionCreds)).sign(request) ); } @Test public void sign_withQuery_withNoContentHashHeader_throws() { SdkHttpRequest.Builder request = getRequest().removeHeader("x-amz-content-sha256"); assertThrows(IllegalArgumentException.class, () -> query(getProperties(sessionCreds)).sign(request) ); } private V4Properties getProperties(AwsCredentialsIdentity creds) { Clock clock = new TickingClock(Instant.EPOCH); return V4Properties.builder() .credentials(creds) .credentialScope(new CredentialScope("us-east-1", "demo", clock.instant())) .signingClock(clock) .doubleUrlEncode(false) .normalizePath(false) .build(); } private SdkHttpRequest.Builder getRequest() { URI target = URI.create("https://test.com/./foo"); return SdkHttpRequest.builder() .method(SdkHttpMethod.GET) .uri(target) .encodedPath(target.getPath()) .putHeader("x-amz-content-sha256", "checksum") .putHeader("x-amz-archive-description", "test test"); } }
2,553
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer/FlexibleChecksummerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.signer; import static org.junit.jupiter.api.Assertions.assertEquals; import static software.amazon.awssdk.checksums.DefaultChecksumAlgorithm.CRC32; import static software.amazon.awssdk.checksums.DefaultChecksumAlgorithm.SHA256; import static software.amazon.awssdk.http.auth.aws.internal.signer.FlexibleChecksummer.option; import io.reactivex.Flowable; import java.io.ByteArrayInputStream; import java.net.URI; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import org.junit.jupiter.api.Test; import org.reactivestreams.Publisher; import software.amazon.awssdk.http.ContentStreamProvider; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.utils.BinaryUtils; public class FlexibleChecksummerTest { ContentStreamProvider payload = () -> new ByteArrayInputStream("foo".getBytes(StandardCharsets.UTF_8)); Publisher<ByteBuffer> payloadAsync = Flowable.just(ByteBuffer.wrap("foo".getBytes(StandardCharsets.UTF_8))); SdkHttpRequest.Builder request = SdkHttpRequest.builder() .uri(URI.create("https://localhost")) .method(SdkHttpMethod.GET); @Test public void checksummer_withNoChecksums_shouldNotAddAnyChecksum() { FlexibleChecksummer checksummer = new FlexibleChecksummer(); SdkHttpRequest expectedRequest = request.build(); checksummer.checksum(payload, request); assertEquals(expectedRequest.headers(), request.build().headers()); } @Test public void checksummerAsync_withNoChecksums_shouldNotAddAnyChecksum() { FlexibleChecksummer checksummer = new FlexibleChecksummer(); SdkHttpRequest expectedRequest = request.build(); checksummer.checksum(payloadAsync, request); assertEquals(expectedRequest.headers(), request.build().headers()); } @Test public void checksummer_withOneChecksum_shouldAddOneChecksum() { FlexibleChecksummer checksummer = new FlexibleChecksummer( option().headerName("sha256").algorithm(SHA256).formatter(BinaryUtils::toHex).build() ); SdkHttpRequest expectedRequest = request .putHeader("sha256", "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae") .build(); checksummer.checksum(payload, request); assertEquals(expectedRequest.headers(), request.build().headers()); } @Test public void checksummerAsync_withOneChecksum_shouldAddOneChecksum() { FlexibleChecksummer checksummer = new FlexibleChecksummer( option().headerName("sha256").algorithm(SHA256).formatter(BinaryUtils::toBase64).build() ); SdkHttpRequest expectedRequest = request .putHeader("sha256", "LCa0a2j/xo/5m0U8HTBBNBNCLXBkg7+g+YpeiGJm564=") .build(); checksummer.checksum(payloadAsync, request); assertEquals(expectedRequest.headers(), request.build().headers()); } @Test public void checksummer_withTwoChecksums_shouldAddTwoChecksums() { FlexibleChecksummer checksummer = new FlexibleChecksummer( option().headerName("sha256").algorithm(SHA256).formatter(BinaryUtils::toHex).build(), option().headerName("crc32").algorithm(CRC32).formatter(BinaryUtils::toBase64).build() ); SdkHttpRequest expectedRequest = request .putHeader("sha256", "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae") .putHeader("crc32", "jHNlIQ==") .build(); checksummer.checksum(payload, request); assertEquals(expectedRequest.headers(), request.build().headers()); } @Test public void checksummerAsync_withTwoChecksums_shouldAddTwoChecksums() { FlexibleChecksummer checksummer = new FlexibleChecksummer( option().headerName("sha256").algorithm(SHA256).formatter(BinaryUtils::toBase64).build(), option().headerName("crc32").algorithm(CRC32).formatter(BinaryUtils::toHex).build() ); SdkHttpRequest expectedRequest = request .putHeader("sha256", "LCa0a2j/xo/5m0U8HTBBNBNCLXBkg7+g+YpeiGJm564=") .putHeader("crc32", "8c736521") .build(); checksummer.checksum(payloadAsync, request); assertEquals(expectedRequest.headers(), request.build().headers()); } }
2,554
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer/PrecomputedSha256ChecksummerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.signer; import static org.junit.jupiter.api.Assertions.assertEquals; import io.reactivex.Flowable; import java.io.ByteArrayInputStream; import java.net.URI; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import org.junit.jupiter.api.Test; import org.reactivestreams.Publisher; import software.amazon.awssdk.http.ContentStreamProvider; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; public class PrecomputedSha256ChecksummerTest { ContentStreamProvider payload = () -> new ByteArrayInputStream("foo".getBytes(StandardCharsets.UTF_8)); Publisher<ByteBuffer> payloadAsync = Flowable.just(ByteBuffer.wrap("foo".getBytes(StandardCharsets.UTF_8))); SdkHttpRequest.Builder request = SdkHttpRequest.builder() .uri(URI.create("https://localhost")) .method(SdkHttpMethod.GET); @Test public void checksummer_shouldAddComputedValue() { PrecomputedSha256Checksummer checksummer = new PrecomputedSha256Checksummer(() -> "something"); SdkHttpRequest expectedRequest = request .putHeader("x-amz-content-sha256", "something") .build(); checksummer.checksum(payload, request); assertEquals(expectedRequest.toString(), request.build().toString()); } @Test public void checksummerAsync_shouldAddComputedValue() { PrecomputedSha256Checksummer checksummer = new PrecomputedSha256Checksummer(() -> "something"); SdkHttpRequest expectedRequest = request .putHeader("x-amz-content-sha256", "something") .build(); checksummer.checksum(payloadAsync, request); assertEquals(expectedRequest.toString(), request.build().toString()); } }
2,555
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer/util/SignerKeyTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.signer.util; import static org.assertj.core.api.Assertions.assertThat; import java.time.Instant; import org.junit.jupiter.api.Test; public class SignerKeyTest { @Test public void isValidForDate_dayBefore_false() { Instant signerDate = Instant.parse("2020-03-03T23:59:59Z"); SignerKey key = new SignerKey(signerDate, new byte[0]); Instant dayBefore = Instant.parse("2020-03-02T23:59:59Z"); assertThat(key.isValidForDate(dayBefore)).isFalse(); } @Test public void isValidForDate_sameDay_true() { Instant signerDate = Instant.parse("2020-03-03T23:59:59Z"); SignerKey key = new SignerKey(signerDate, new byte[0]); Instant sameDay = Instant.parse("2020-03-03T01:02:03Z"); assertThat(key.isValidForDate(sameDay)).isTrue(); } @Test public void isValidForDate_dayAfter_false() { Instant signerDate = Instant.parse("2020-03-03T23:59:59Z"); SignerKey key = new SignerKey(signerDate, new byte[0]); Instant dayAfter = Instant.parse("2020-03-04T00:00:00Z"); assertThat(key.isValidForDate(dayAfter)).isFalse(); } }
2,556
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer/util/FifoCacheTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.signer.util; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; public class FifoCacheTest { @Test public void test() { FifoCache<String> cache = new FifoCache<>(3); assertEquals(0, cache.size()); cache.add("k1", "v1"); assertEquals(1, cache.size()); cache.add("k1", "v11"); assertEquals(1, cache.size()); cache.add("k2", "v2"); assertEquals(2, cache.size()); cache.add("k3", "v3"); assertEquals(3, cache.size()); assertEquals("v11", cache.get("k1")); assertEquals("v2", cache.get("k2")); assertEquals("v3", cache.get("k3")); cache.add("k4", "v4"); assertEquals(3, cache.size()); assertNull(cache.get("k1")); } @Test public void testZeroSize() { assertThrows(IllegalArgumentException.class, () -> new FifoCache<>(0)); } @Test public void testIllegalArgument() { assertThrows(IllegalArgumentException.class, () -> new FifoCache<>(0)); } @Test public void testSingleEntry() { FifoCache<String> cache = new FifoCache<String>(1); assertEquals(0, cache.size()); cache.add("k1", "v1"); assertEquals(1, cache.size()); cache.add("k1", "v11"); assertEquals(1, cache.size()); assertEquals("v11", cache.get("k1")); cache.add("k2", "v2"); assertEquals(1, cache.size()); assertEquals("v2", cache.get("k2")); assertNull(cache.get("k1")); cache.add("k3", "v3"); assertEquals(1, cache.size()); assertEquals("v3", cache.get("k3")); assertNull(cache.get("k2")); } }
2,557
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer/util/ChecksumUtilTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.signer.util; import static org.junit.jupiter.api.Assertions.assertEquals; import static software.amazon.awssdk.checksums.DefaultChecksumAlgorithm.CRC32; import static software.amazon.awssdk.checksums.DefaultChecksumAlgorithm.CRC32C; import static software.amazon.awssdk.checksums.DefaultChecksumAlgorithm.MD5; import static software.amazon.awssdk.checksums.DefaultChecksumAlgorithm.SHA1; import static software.amazon.awssdk.checksums.DefaultChecksumAlgorithm.SHA256; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.ChecksumUtil.checksumHeaderName; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.ChecksumUtil.fromChecksumAlgorithm; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.ChecksumUtil.readAll; import java.io.ByteArrayInputStream; import org.junit.jupiter.api.Test; import software.amazon.awssdk.http.auth.aws.internal.signer.checksums.Crc32CChecksum; import software.amazon.awssdk.http.auth.aws.internal.signer.checksums.Crc32Checksum; import software.amazon.awssdk.http.auth.aws.internal.signer.checksums.Md5Checksum; import software.amazon.awssdk.http.auth.aws.internal.signer.checksums.Sha1Checksum; import software.amazon.awssdk.http.auth.aws.internal.signer.checksums.Sha256Checksum; public class ChecksumUtilTest { @Test public void checksumHeaderName_shouldFormatName() { assertEquals("x-amz-checksum-sha256", checksumHeaderName(SHA256)); assertEquals("x-amz-checksum-sha1", checksumHeaderName(SHA1)); assertEquals("x-amz-checksum-crc32", checksumHeaderName(CRC32)); assertEquals("x-amz-checksum-crc32c", checksumHeaderName(CRC32C)); assertEquals("x-amz-checksum-md5", checksumHeaderName(MD5)); } @Test public void fromChecksumAlgorithm_mapsToCorrectSdkChecksum() { assertEquals(Sha256Checksum.class, fromChecksumAlgorithm(SHA256).getClass()); assertEquals(Sha1Checksum.class, fromChecksumAlgorithm(SHA1).getClass()); assertEquals(Crc32Checksum.class, fromChecksumAlgorithm(CRC32).getClass()); assertEquals(Crc32CChecksum.class, fromChecksumAlgorithm(CRC32C).getClass()); assertEquals(Md5Checksum.class, fromChecksumAlgorithm(MD5).getClass()); } @Test public void readAll_consumesEntireStream() { int bytes = 4096 * 4 + 1; byte[] buf = new byte[bytes]; ByteArrayInputStream inputStream = new ByteArrayInputStream(buf); readAll(inputStream); assertEquals(0, inputStream.available()); } }
2,558
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer/io/ChecksumInputStreamTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.signer.io; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.ChecksumUtil.readAll; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import org.junit.jupiter.api.Test; import software.amazon.awssdk.http.auth.aws.internal.signer.checksums.Crc32Checksum; import software.amazon.awssdk.http.auth.aws.internal.signer.checksums.SdkChecksum; import software.amazon.awssdk.http.auth.aws.internal.signer.checksums.Sha256Checksum; import software.amazon.awssdk.utils.BinaryUtils; public class ChecksumInputStreamTest { @Test public void read_computesCorrectSha256() { String testString = "AWS SDK for Java"; String expectedDigest = "004c6bbd87e7fe70109b3bc23c8b1ab8f18a8bede0ed38c9233f6cdfd4f7b5d6"; ByteArrayInputStream backingStream = new ByteArrayInputStream(testString.getBytes(StandardCharsets.UTF_8)); SdkChecksum checksum = new Sha256Checksum(); ChecksumInputStream inputStream = new ChecksumInputStream(backingStream, Collections.singleton(checksum)); readAll(inputStream); String computedDigest = BinaryUtils.toHex(checksum.getChecksumBytes()); assertThat(computedDigest).isEqualTo(expectedDigest); } @Test public void read_withMultipleChecksums_shouldComputeCorrectChecksums() { String testString = "AWS SDK for Java"; String expectedSha256Digest = "004c6bbd87e7fe70109b3bc23c8b1ab8f18a8bede0ed38c9233f6cdfd4f7b5d6"; String expectedCrc32Digest = "4ac37ece"; ByteArrayInputStream backingStream = new ByteArrayInputStream(testString.getBytes(StandardCharsets.UTF_8)); SdkChecksum sha256Checksum = new Sha256Checksum(); SdkChecksum crc32Checksum = new Crc32Checksum(); ChecksumInputStream inputStream = new ChecksumInputStream(backingStream, Arrays.asList(sha256Checksum, crc32Checksum)); readAll(inputStream); String computedSha256Digest = BinaryUtils.toHex(sha256Checksum.getChecksumBytes()); String computedCrc32Digest = BinaryUtils.toHex(crc32Checksum.getChecksumBytes()); assertThat(computedSha256Digest).isEqualTo(expectedSha256Digest); assertThat(computedCrc32Digest).isEqualTo(expectedCrc32Digest); } }
2,559
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer/io/ChunkInputStreamTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.signer.io; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayInputStream; import java.io.IOException; import org.junit.jupiter.api.Test; import software.amazon.awssdk.http.auth.aws.internal.signer.chunkedencoding.ChunkInputStream; public class ChunkInputStreamTest { @Test public void close_shouldDrainChunk() throws IOException { ByteArrayInputStream backingStream = new ByteArrayInputStream(new byte[] {'a', 'b', 'c', 'd', 'e', 'f', 'g'}); ChunkInputStream in = new ChunkInputStream(backingStream, 5); in.close(); assertEquals(0, in.remaining()); assertEquals(2, backingStream.available()); } }
2,560
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer/io/ChecksumSubscriberTckTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.signer.io; import java.nio.ByteBuffer; import java.util.Collections; import org.reactivestreams.Subscriber; import org.reactivestreams.tck.TestEnvironment; import software.amazon.awssdk.http.auth.aws.internal.signer.checksums.Sha256Checksum; /** * TCK verifiation test for {@link ChecksumSubscriber}. */ public class ChecksumSubscriberTckTest extends org.reactivestreams.tck.SubscriberBlackboxVerification<ByteBuffer> { public ChecksumSubscriberTckTest() { super(new TestEnvironment()); } @Override public Subscriber<ByteBuffer> createSubscriber() { return new ChecksumSubscriber(Collections.singleton(new Sha256Checksum())); } @Override public ByteBuffer createElement(int i) { return ByteBuffer.wrap(String.valueOf(i).getBytes()); } }
2,561
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer/io/ChecksumSubscriberTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.signer.io; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static software.amazon.awssdk.utils.CompletableFutureUtils.joinLikeSync; import io.reactivex.Flowable; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import org.junit.jupiter.api.Test; import org.reactivestreams.Subscription; import software.amazon.awssdk.http.auth.aws.internal.signer.checksums.Crc32Checksum; import software.amazon.awssdk.http.auth.aws.internal.signer.checksums.SdkChecksum; import software.amazon.awssdk.http.auth.aws.internal.signer.checksums.Sha256Checksum; import software.amazon.awssdk.utils.BinaryUtils; public class ChecksumSubscriberTest { @Test public void checksum_computesCorrectSha256() { String testString = "AWS SDK for Java"; String expectedDigest = "004c6bbd87e7fe70109b3bc23c8b1ab8f18a8bede0ed38c9233f6cdfd4f7b5d6"; SdkChecksum checksum = new Sha256Checksum(); ChecksumSubscriber subscriber = new ChecksumSubscriber(Collections.singleton(checksum)); Flowable<ByteBuffer> publisher = Flowable.just(ByteBuffer.wrap(testString.getBytes(StandardCharsets.UTF_8))); publisher.subscribe(subscriber); joinLikeSync(subscriber.completeFuture()); String computedDigest = BinaryUtils.toHex(checksum.getChecksumBytes()); assertThat(computedDigest).isEqualTo(expectedDigest); } @Test public void checksum_withMultipleChecksums_shouldComputeCorrectChecksums() { String testString = "AWS SDK for Java"; String expectedSha256Digest = "004c6bbd87e7fe70109b3bc23c8b1ab8f18a8bede0ed38c9233f6cdfd4f7b5d6"; String expectedCrc32Digest = "4ac37ece"; SdkChecksum sha256Checksum = new Sha256Checksum(); SdkChecksum crc32Checksum = new Crc32Checksum(); ChecksumSubscriber subscriber = new ChecksumSubscriber(Arrays.asList(sha256Checksum, crc32Checksum)); Flowable<ByteBuffer> publisher = Flowable.just(ByteBuffer.wrap(testString.getBytes(StandardCharsets.UTF_8))); publisher.subscribe(subscriber); joinLikeSync(subscriber.completeFuture()); String computedSha256Digest = BinaryUtils.toHex(sha256Checksum.getChecksumBytes()); String computedCrc32Digest = BinaryUtils.toHex(crc32Checksum.getChecksumBytes()); assertThat(computedSha256Digest).isEqualTo(expectedSha256Digest); assertThat(computedCrc32Digest).isEqualTo(expectedCrc32Digest); } @Test public void checksum_futureCancelledBeforeSubscribe_cancelsSubscription() { Subscription mockSubscription = mock(Subscription.class); ChecksumSubscriber subscriber = new ChecksumSubscriber(Collections.emptyList()); subscriber.completeFuture().cancel(true); subscriber.onSubscribe(mockSubscription); verify(mockSubscription).cancel(); verify(mockSubscription, times(0)).request(anyLong()); } @Test public void checksum_publisherCallsOnError_errorPropagatedToFuture() { Subscription mockSubscription = mock(Subscription.class); ChecksumSubscriber subscriber = new ChecksumSubscriber(Collections.emptyList()); subscriber.onSubscribe(mockSubscription); RuntimeException error = new RuntimeException("error"); subscriber.onError(error); assertThatThrownBy(subscriber.completeFuture()::join).hasCause(error); } }
2,562
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/internal/signer/chunkedencoding/ChunkedEncodedInputStreamTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.signer.chunkedencoding; import static java.util.Arrays.copyOf; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static software.amazon.awssdk.http.auth.aws.internal.signer.V4CanonicalRequest.getCanonicalHeadersString; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerUtils.deriveSigningKey; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerUtils.hash; import static software.amazon.awssdk.utils.BinaryUtils.toHex; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.function.Function; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import software.amazon.awssdk.http.auth.aws.internal.signer.CredentialScope; import software.amazon.awssdk.http.auth.aws.internal.signer.RollingSigner; import software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerConstant; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.utils.Pair; public class ChunkedEncodedInputStreamTest { @Test public void ChunkEncodedInputStream_withBasicParams_returnsEncodedChunks() throws IOException { byte[] data = "abcdefghij".getBytes(); InputStream payload = new ByteArrayInputStream(data); int chunkSize = 3; ChunkedEncodedInputStream inputStream = ChunkedEncodedInputStream .builder() .inputStream(payload) .chunkSize(chunkSize) .header(chunk -> Integer.toHexString(chunk.length).getBytes()) .build(); byte[] tmp = new byte[64]; int bytesRead = readAll(inputStream, tmp); int expectedBytesRead = 35; byte[] expected = new byte[expectedBytesRead]; System.arraycopy( "3\r\nabc\r\n3\r\ndef\r\n3\r\nghi\r\n1\r\nj\r\n0\r\n\r\n".getBytes(), 0, expected, 0, expectedBytesRead ); byte[] actual = copyOf(tmp, bytesRead); assertEquals(expectedBytesRead, bytesRead); assertArrayEquals(expected, actual); } @Test public void ChunkEncodedInputStream_withExtensions_returnsEncodedExtendedChunks() throws IOException { byte[] data = "abcdefghij".getBytes(); InputStream payload = new ByteArrayInputStream(data); int chunkSize = 3; ChunkExtensionProvider helloWorldExt = chunk -> Pair.of( "hello".getBytes(StandardCharsets.UTF_8), "world!".getBytes(StandardCharsets.UTF_8) ); ChunkedEncodedInputStream inputStream = ChunkedEncodedInputStream .builder() .inputStream(payload) .chunkSize(chunkSize) .header(chunk -> Integer.toHexString(chunk.length).getBytes()) .extensions(Collections.singletonList(helloWorldExt)) .build(); byte[] tmp = new byte[128]; int bytesRead = readAll(inputStream, tmp); int expectedBytesRead = 100; byte[] expected = new byte[expectedBytesRead]; System.arraycopy( ("3;hello=world!\r\nabc\r\n3;hello=world!\r\ndef\r\n3;hello=world!\r\nghi\r\n" + "1;hello=world!\r\nj\r\n0;hello=world!\r\n\r\n").getBytes(), 0, expected, 0, expectedBytesRead ); byte[] actual = copyOf(tmp, expected.length); assertEquals(expectedBytesRead, bytesRead); assertArrayEquals(expected, actual); } @Test public void ChunkEncodedInputStream_withTrailers_returnsEncodedChunksAndTrailerChunk() throws IOException { byte[] data = "abcdefghij".getBytes(); InputStream payload = new ByteArrayInputStream(data); int chunkSize = 3; TrailerProvider helloWorldTrailer = () -> Pair.of( "hello", Collections.singletonList("world!") ); ChunkedEncodedInputStream inputStream = ChunkedEncodedInputStream .builder() .inputStream(payload) .chunkSize(chunkSize) .header(chunk -> Integer.toHexString(chunk.length).getBytes()) .trailers(Collections.singletonList(helloWorldTrailer)) .build(); byte[] tmp = new byte[64]; int bytesRead = readAll(inputStream, tmp); int expectedBytesRead = 49; byte[] expected = new byte[expectedBytesRead]; System.arraycopy( "3\r\nabc\r\n3\r\ndef\r\n3\r\nghi\r\n1\r\nj\r\n0\r\nhello:world!\r\n\r\n".getBytes(), 0, expected, 0, expectedBytesRead ); byte[] actual = copyOf(tmp, expected.length); assertEquals(expectedBytesRead, bytesRead); assertArrayEquals(expected, actual); } @Test public void ChunkEncodedInputStream_withExtensionsAndTrailers_EncodedExtendedChunksAndTrailerChunk() throws IOException { byte[] data = "abcdefghij".getBytes(); InputStream payload = new ByteArrayInputStream(data); int chunkSize = 3; ChunkExtensionProvider aExt = chunk -> Pair.of("a".getBytes(StandardCharsets.UTF_8), "1".getBytes(StandardCharsets.UTF_8)); ChunkExtensionProvider bExt = chunk -> Pair.of("b".getBytes(StandardCharsets.UTF_8), "2".getBytes(StandardCharsets.UTF_8)); TrailerProvider aTrailer = () -> Pair.of("a", Collections.singletonList("1")); TrailerProvider bTrailer = () -> Pair.of("b", Collections.singletonList("2")); ChunkedEncodedInputStream inputStream = ChunkedEncodedInputStream .builder() .inputStream(payload) .chunkSize(chunkSize) .header(chunk -> Integer.toHexString(chunk.length).getBytes()) .addExtension(aExt) .addExtension(bExt) .addTrailer(aTrailer) .addTrailer(bTrailer) .build(); byte[] tmp = new byte[128]; int bytesRead = readAll(inputStream, tmp); int expectedBytesRead = 85; byte[] expected = new byte[expectedBytesRead]; System.arraycopy( "3;a=1;b=2\r\nabc\r\n3;a=1;b=2\r\ndef\r\n3;a=1;b=2\r\nghi\r\n1;a=1;b=2\r\nj\r\n0;a=1;b=2\r\na:1\r\nb:2\r\n\r\n".getBytes(), 0, expected, 0, expectedBytesRead ); byte[] actual = copyOf(tmp, expected.length); assertEquals(expectedBytesRead, bytesRead); assertArrayEquals(expected, actual); } @Test public void ChunkEncodedInputStream_withAwsParams_returnsAwsSignedAndEncodedChunks() throws IOException { byte[] data = new byte[65 * 1024]; Arrays.fill(data, (byte) 'a'); String seedSignature = "106e2a8a18243abcf37539882f36619c00e2dfc72633413f02d3b74544bfeb8e"; CredentialScope credentialScope = new CredentialScope("us-east-1", "s3", Instant.parse("2013-05-24T00:00:00Z")); AwsCredentialsIdentity credentials = AwsCredentialsIdentity.create("AKIAIOSFODNN7EXAMPLE", "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"); byte[] signingKey = deriveSigningKey(credentials, credentialScope); InputStream payload = new ByteArrayInputStream(data); int chunkSize = 64 * 1024; RollingSigner signer = new RollingSigner(signingKey, seedSignature); ChunkExtensionProvider ext = chunk -> Pair.of( "chunk-signature".getBytes(StandardCharsets.UTF_8), signer.sign(previousSignature -> "AWS4-HMAC-SHA256-PAYLOAD" + SignerConstant.LINE_SEPARATOR + credentialScope.getDatetime() + SignerConstant.LINE_SEPARATOR + credentialScope.scope() + SignerConstant.LINE_SEPARATOR + previousSignature + SignerConstant.LINE_SEPARATOR + toHex(hash("")) + SignerConstant.LINE_SEPARATOR + toHex(hash(chunk))) .getBytes(StandardCharsets.UTF_8) ); TrailerProvider checksumTrailer = () -> Pair.of( "x-amz-checksum-crc32c", Collections.singletonList("wdBDMA==") ); List<Pair<String, List<String>>> trailers = Collections.singletonList(checksumTrailer.get()); Function<String, String> template = previousSignature -> "AWS4-HMAC-SHA256-TRAILER" + SignerConstant.LINE_SEPARATOR + credentialScope.getDatetime() + SignerConstant.LINE_SEPARATOR + credentialScope.scope() + SignerConstant.LINE_SEPARATOR + previousSignature + SignerConstant.LINE_SEPARATOR + toHex(hash(getCanonicalHeadersString(trailers))); TrailerProvider signatureTrailer = () -> Pair.of( "x-amz-trailer-signature", Collections.singletonList(signer.sign(template)) ); ChunkedEncodedInputStream inputStream = ChunkedEncodedInputStream .builder() .inputStream(payload) .chunkSize(chunkSize) .header(chunk -> Integer.toHexString(chunk.length).getBytes()) .extensions(Collections.singletonList(ext)) .trailers(Arrays.asList(checksumTrailer, signatureTrailer)) .build(); byte[] tmp = new byte[chunkSize * 4]; int bytesRead = readAll(inputStream, tmp); int expectedBytesRead = 66946; byte[] actualBytes = copyOf(tmp, expectedBytesRead); ByteArrayOutputStream expected = new ByteArrayOutputStream(); expected.write( "10000;chunk-signature=b474d8862b1487a5145d686f57f013e54db672cee1c953b3010fb58501ef5aa2\r\n".getBytes( StandardCharsets.UTF_8) ); expected.write(data, 0, chunkSize); expected.write( "\r\n400;chunk-signature=1c1344b170168f8e65b41376b44b20fe354e373826ccbbe2c1d40a8cae51e5c7\r\n".getBytes( StandardCharsets.UTF_8) ); expected.write(data, chunkSize, 1024); expected.write( "\r\n0;chunk-signature=2ca2aba2005185cf7159c6277faf83795951dd77a3a99e6e65d5c9f85863f992\r\n".getBytes( StandardCharsets.UTF_8) ); expected.write(( "x-amz-checksum-crc32c:wdBDMA==\r\n" + "x-amz-trailer-signature:ce306fa4cdf73aa89071b78358f0d22ea79c43117314c8ed68017f7d6f91048e\r\n" + "\r\n").getBytes(StandardCharsets.UTF_8) ); assertEquals(expectedBytesRead, bytesRead); assertArrayEquals(expected.toByteArray(), actualBytes); } @ParameterizedTest @ValueSource(ints = {1, 2, 3, 5, 8, 13, 21, 24, 45, 69, 104}) void ChunkEncodedInputStream_withVariableChunkSize_shouldCorrectlyChunkData(int chunkSize) throws IOException { int size = 100; byte[] data = new byte[size]; Arrays.fill(data, (byte) 'a'); ChunkedEncodedInputStream inputStream = ChunkedEncodedInputStream .builder() .inputStream(new ByteArrayInputStream(data)) .header(chunk -> new byte[] {'0'}) .chunkSize(chunkSize) .build(); int expectedBytesRead = 0; int numChunks = size / chunkSize; // 0\r\n<data>\r\n expectedBytesRead += numChunks * (5 + chunkSize); if (size % chunkSize != 0) { // 0\r\n\<left-over>\r\n expectedBytesRead += 5 + (size % chunkSize); } // 0\r\n\r\n expectedBytesRead += 5; byte[] tmp = new byte[expectedBytesRead]; int bytesRead = readAll(inputStream, tmp); assertEquals(expectedBytesRead, bytesRead); } private int readAll(InputStream src, byte[] dst) throws IOException { int read = 0; int offset = 0; while (read >= 0) { read = src.read(); if (read >= 0) { dst[offset] = (byte) read; offset += 1; } } return offset; } }
2,563
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/crt/TestUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 static software.amazon.awssdk.http.auth.aws.signer.AwsV4aHttpSigner.REGION_SET; import static software.amazon.awssdk.http.auth.aws.signer.AwsV4aHttpSigner.SERVICE_SIGNING_NAME; import static software.amazon.awssdk.http.auth.aws.TestUtils.TickingClock; import static software.amazon.awssdk.http.auth.aws.crt.internal.util.CrtHttpRequestConverter.toRequest; import static software.amazon.awssdk.http.auth.aws.crt.internal.util.CrtUtils.sanitizeRequest; import static software.amazon.awssdk.http.auth.aws.crt.internal.util.CrtUtils.toCredentials; import static software.amazon.awssdk.http.auth.spi.signer.HttpSigner.SIGNING_CLOCK; import java.io.ByteArrayInputStream; import java.net.URI; import java.time.Instant; import java.util.function.Consumer; 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.ContentStreamProvider; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.auth.aws.signer.RegionSet; import software.amazon.awssdk.http.auth.spi.signer.SignRequest; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; public final class TestUtils { private static final String TEST_VERIFICATION_PUB_X = "b6618f6a65740a99e650b33b6b4b5bd0d43b176d721a3edfea7e7d2d56d936b1"; private static final String TEST_VERIFICATION_PUB_Y = "865ed22a7eadc9c5cb9d2cbaca1b3699139fedc5043dc6661864218330c8e518"; private TestUtils() { } // Helpers for generating test requests public static <T extends AwsCredentialsIdentity> SignRequest<T> generateBasicRequest( T credentials, Consumer<? super SdkHttpRequest.Builder> requestOverrides, Consumer<? super SignRequest.Builder<T>> signRequestOverrides ) { return SignRequest.builder(credentials) .request(SdkHttpRequest.builder() .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")) .build() .copy(requestOverrides)) .payload(() -> new ByteArrayInputStream("{\"TableName\": \"foo\"}".getBytes())) .putProperty(REGION_SET, RegionSet.create("aws-global")) .putProperty(SERVICE_SIGNING_NAME, "demo") .putProperty(SIGNING_CLOCK, new TickingClock(Instant.ofEpochMilli(1596476903000L))) .build() .copy(signRequestOverrides); } public static AwsSigningConfig generateBasicSigningConfig(AwsCredentialsIdentity credentials) { try (AwsSigningConfig signingConfig = new AwsSigningConfig()) { signingConfig.setCredentials(toCredentials(credentials)); signingConfig.setService("demo"); signingConfig.setRegion("aws-global"); signingConfig.setAlgorithm(AwsSigningConfig.AwsSigningAlgorithm.SIGV4_ASYMMETRIC); signingConfig.setTime(1596476903000L); signingConfig.setUseDoubleUriEncode(true); signingConfig.setShouldNormalizeUriPath(true); return signingConfig; } } public static boolean verifyEcdsaSignature(SdkHttpRequest request, ContentStreamProvider payload, String expectedCanonicalRequest, AwsSigningConfig signingConfig, String signatureValue) { HttpRequest crtRequest = toRequest(sanitizeRequest(request), payload); return AwsSigningUtils.verifySigv4aEcdsaSignature(crtRequest, expectedCanonicalRequest, signingConfig, signatureValue.getBytes(), TEST_VERIFICATION_PUB_X, TEST_VERIFICATION_PUB_Y); } }
2,564
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/crt/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/crt/internal/signer/AwsChunkedV4aPayloadSignerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.signer; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static software.amazon.awssdk.checksums.DefaultChecksumAlgorithm.CRC32; import static software.amazon.awssdk.http.auth.aws.crt.internal.util.CrtUtils.toCredentials; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerConstant.STREAMING_ECDSA_SIGNED_PAYLOAD; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerConstant.STREAMING_ECDSA_SIGNED_PAYLOAD_TRAILER; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerConstant.STREAMING_UNSIGNED_PAYLOAD_TRAILER; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.nio.charset.StandardCharsets; import java.time.Instant; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.crt.auth.signing.AwsSigningConfig; import software.amazon.awssdk.http.ContentStreamProvider; import software.amazon.awssdk.http.Header; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.auth.aws.internal.signer.CredentialScope; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; /** * Test the delegation of signing to the correct implementations. */ public class AwsChunkedV4aPayloadSignerTest { private static final int CHUNK_SIZE = 4; private static final CredentialScope CREDENTIAL_SCOPE = new CredentialScope("us-east-1", "s3", Instant.EPOCH); private static final byte[] DATA = "{\"TableName\": \"foo\"}".getBytes(); private static final ContentStreamProvider PAYLOAD = () -> new ByteArrayInputStream(DATA); private SdkHttpRequest.Builder requestBuilder; @BeforeEach public void setUp() { requestBuilder = SdkHttpRequest .builder() .method(SdkHttpMethod.POST) .putHeader("Host", "demo.us-east-1.amazonaws.com") .putHeader("x-amz-archive-description", "test test") .putHeader(Header.CONTENT_LENGTH, Integer.toString(DATA.length)) .encodedPath("/") .uri(URI.create("http://demo.us-east-1.amazonaws.com")); } @Test public void sign_withSignedPayload_shouldChunkEncodeWithSigV4aExt() throws IOException { AwsSigningConfig signingConfig = basicSigningConfig(); signingConfig.setSignedBodyValue(STREAMING_ECDSA_SIGNED_PAYLOAD); V4aRequestSigningResult result = new V4aRequestSigningResult( requestBuilder, "sig".getBytes(StandardCharsets.UTF_8), signingConfig ); AwsChunkedV4aPayloadSigner signer = AwsChunkedV4aPayloadSigner.builder() .credentialScope(CREDENTIAL_SCOPE) .chunkSize(CHUNK_SIZE) .build(); signer.beforeSigning(requestBuilder, PAYLOAD, signingConfig.getSignedBodyValue()); ContentStreamProvider signedPayload = signer.sign(PAYLOAD, result); assertThat(requestBuilder.firstMatchingHeader("x-amz-decoded-content-length")).hasValue(Integer.toString(DATA.length)); byte[] tmp = new byte[2048]; int actualBytes = readAll(signedPayload.newStream(), tmp); int expectedBytes = expectedByteCount(DATA, CHUNK_SIZE); assertThat(requestBuilder.firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue(Integer.toString(actualBytes)); assertEquals(expectedBytes, actualBytes); } @Test public void sign_withSignedPayloadAndChecksum_shouldChunkEncodeWithSigV4aExtAndSigV4aTrailer() throws IOException { AwsSigningConfig signingConfig = basicSigningConfig(); signingConfig.setSignedBodyValue(STREAMING_ECDSA_SIGNED_PAYLOAD_TRAILER); V4aRequestSigningResult result = new V4aRequestSigningResult( requestBuilder, "sig".getBytes(StandardCharsets.UTF_8), signingConfig ); AwsChunkedV4aPayloadSigner signer = AwsChunkedV4aPayloadSigner.builder() .credentialScope(CREDENTIAL_SCOPE) .chunkSize(CHUNK_SIZE) .checksumAlgorithm(CRC32) .build(); signer.beforeSigning(requestBuilder, PAYLOAD, signingConfig.getSignedBodyValue()); ContentStreamProvider signedPayload = signer.sign(PAYLOAD, result); assertThat(requestBuilder.firstMatchingHeader("x-amz-decoded-content-length")).hasValue(Integer.toString(DATA.length)); assertThat(requestBuilder.firstMatchingHeader("x-amz-trailer")).hasValue("x-amz-checksum-crc32"); byte[] tmp = new byte[2048]; int actualBytes = readAll(signedPayload.newStream(), tmp); int expectedBytes = expectedByteCount(DATA, CHUNK_SIZE); // include trailer bytes in the count: // (checksum-header + checksum-value + \r\n + trailer-sig-header + trailer-sig + \r\n) expectedBytes += 21 + 8 + 2 + 24 + 144 + 2; assertThat(requestBuilder.firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue(Integer.toString(actualBytes)); assertEquals(expectedBytes, actualBytes); } @Test public void sign_withChecksum_shouldChunkEncodeWithChecksumTrailer() throws IOException { AwsSigningConfig signingConfig = basicSigningConfig(); signingConfig.setSignedBodyValue(STREAMING_UNSIGNED_PAYLOAD_TRAILER); V4aRequestSigningResult result = new V4aRequestSigningResult( requestBuilder, "sig".getBytes(StandardCharsets.UTF_8), signingConfig ); AwsChunkedV4aPayloadSigner signer = AwsChunkedV4aPayloadSigner.builder() .credentialScope(CREDENTIAL_SCOPE) .chunkSize(CHUNK_SIZE) .checksumAlgorithm(CRC32) .build(); signer.beforeSigning(requestBuilder, PAYLOAD, signingConfig.getSignedBodyValue()); ContentStreamProvider signedPayload = signer.sign(PAYLOAD, result); assertThat(requestBuilder.firstMatchingHeader("x-amz-decoded-content-length")).hasValue(Integer.toString(DATA.length)); assertThat(requestBuilder.firstMatchingHeader("x-amz-trailer")).hasValue("x-amz-checksum-crc32"); byte[] tmp = new byte[2048]; int actualBytes = readAll(signedPayload.newStream(), tmp); int expectedBytes = expectedByteCountUnsigned(DATA, CHUNK_SIZE); // include trailer bytes in the count: // (checksum-header + checksum-value + \r\n) expectedBytes += 21 + 8 + 2; assertThat(requestBuilder.firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue(Integer.toString(actualBytes)); assertEquals(expectedBytes, actualBytes); } @Test public void sign_withPreExistingTrailers_shouldChunkEncodeWithExistingTrailers() throws IOException { AwsSigningConfig signingConfig = basicSigningConfig(); signingConfig.setSignedBodyValue(STREAMING_UNSIGNED_PAYLOAD_TRAILER); V4aRequestSigningResult result = new V4aRequestSigningResult( requestBuilder .putHeader("x-amz-trailer", "aTrailer") .putHeader("aTrailer", "aValue"), "sig".getBytes(StandardCharsets.UTF_8), signingConfig ); AwsChunkedV4aPayloadSigner signer = AwsChunkedV4aPayloadSigner.builder() .credentialScope(CREDENTIAL_SCOPE) .chunkSize(CHUNK_SIZE) .build(); signer.beforeSigning(requestBuilder, PAYLOAD, signingConfig.getSignedBodyValue()); ContentStreamProvider signedPayload = signer.sign(PAYLOAD, result); assertThat(requestBuilder.firstMatchingHeader("x-amz-decoded-content-length")).hasValue(Integer.toString(DATA.length)); assertThat(requestBuilder.firstMatchingHeader("aTrailer")).isNotPresent(); assertThat(requestBuilder.firstMatchingHeader("x-amz-trailer")).hasValue("aTrailer"); byte[] tmp = new byte[2048]; int actualBytes = readAll(signedPayload.newStream(), tmp); int expectedBytes = expectedByteCountUnsigned(DATA, CHUNK_SIZE); // include trailer bytes in the count: // (aTrailer: + aValue + \r\n) expectedBytes += 9 + 6 + 2; assertThat(requestBuilder.firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue(Integer.toString(actualBytes)); assertEquals(expectedBytes, actualBytes); } @Test public void sign_withPreExistingTrailersAndChecksum_shouldChunkEncodeWithTrailers() throws IOException { AwsSigningConfig signingConfig = basicSigningConfig(); signingConfig.setSignedBodyValue(STREAMING_UNSIGNED_PAYLOAD_TRAILER); V4aRequestSigningResult result = new V4aRequestSigningResult( requestBuilder .putHeader("x-amz-trailer", "aTrailer") .putHeader("aTrailer", "aValue"), "sig".getBytes(StandardCharsets.UTF_8), signingConfig ); AwsChunkedV4aPayloadSigner signer = AwsChunkedV4aPayloadSigner.builder() .credentialScope(CREDENTIAL_SCOPE) .chunkSize(CHUNK_SIZE) .checksumAlgorithm(CRC32) .build(); signer.beforeSigning(requestBuilder, PAYLOAD, signingConfig.getSignedBodyValue()); ContentStreamProvider signedPayload = signer.sign(PAYLOAD, result); assertThat(requestBuilder.firstMatchingHeader("x-amz-decoded-content-length")).hasValue(Integer.toString(DATA.length)); assertThat(requestBuilder.firstMatchingHeader("aTrailer")).isNotPresent(); assertThat(requestBuilder.matchingHeaders("x-amz-trailer")).contains("aTrailer", "x-amz-checksum-crc32"); byte[] tmp = new byte[2048]; int actualBytes = readAll(signedPayload.newStream(), tmp); int expectedBytes = expectedByteCountUnsigned(DATA, CHUNK_SIZE); // include trailer bytes in the count: // (aTrailer: + aValue + \r\n + checksum-header + checksum-value + \r\n) expectedBytes += 9 + 6 + 2 + 21 + 8 + 2; assertThat(requestBuilder.firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue(Integer.toString(actualBytes)); assertEquals(expectedBytes, actualBytes); } @Test public void sign_withPreExistingTrailersAndChecksumAndSignedPayload_shouldAwsChunkEncode() throws IOException { AwsSigningConfig signingConfig = basicSigningConfig(); signingConfig.setSignedBodyValue(STREAMING_ECDSA_SIGNED_PAYLOAD_TRAILER); V4aRequestSigningResult result = new V4aRequestSigningResult( requestBuilder .putHeader("x-amz-trailer", "aTrailer") .putHeader("aTrailer", "aValue"), "sig".getBytes(StandardCharsets.UTF_8), signingConfig ); AwsChunkedV4aPayloadSigner signer = AwsChunkedV4aPayloadSigner.builder() .credentialScope(CREDENTIAL_SCOPE) .chunkSize(CHUNK_SIZE) .checksumAlgorithm(CRC32) .build(); signer.beforeSigning(requestBuilder, PAYLOAD, signingConfig.getSignedBodyValue()); ContentStreamProvider signedPayload = signer.sign(PAYLOAD, result); assertThat(requestBuilder.firstMatchingHeader("x-amz-decoded-content-length")).hasValue(Integer.toString(DATA.length)); assertThat(requestBuilder.firstMatchingHeader("aTrailer")).isNotPresent(); assertThat(requestBuilder.matchingHeaders("x-amz-trailer")).contains("aTrailer", "x-amz-checksum-crc32"); byte[] tmp = new byte[2048]; int actualBytes = readAll(signedPayload.newStream(), tmp); int expectedBytes = expectedByteCount(DATA, CHUNK_SIZE); // include trailer bytes in the count: // (aTrailer: + aValue + \r\n + checksum-header + checksum-value + \r\n + trailer-sig-header + trailer-sig + \r\n) expectedBytes += 9 + 6 + 2 + 21 + 8 + 2 + 24 + 144 + 2; assertThat(requestBuilder.firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue(Integer.toString(actualBytes)); assertEquals(expectedBytes, actualBytes); } @Test public void sign_withoutContentLength_calculatesContentLengthFromPayload() throws IOException { AwsSigningConfig signingConfig = basicSigningConfig(); signingConfig.setSignedBodyValue(STREAMING_UNSIGNED_PAYLOAD_TRAILER); V4aRequestSigningResult result = new V4aRequestSigningResult( requestBuilder, "sig".getBytes(StandardCharsets.UTF_8), signingConfig ); AwsChunkedV4aPayloadSigner signer = AwsChunkedV4aPayloadSigner.builder() .credentialScope(CREDENTIAL_SCOPE) .chunkSize(CHUNK_SIZE) .checksumAlgorithm(CRC32) .build(); requestBuilder.removeHeader(Header.CONTENT_LENGTH); signer.beforeSigning(requestBuilder, PAYLOAD, signingConfig.getSignedBodyValue()); ContentStreamProvider signedPayload = signer.sign(PAYLOAD, result); assertThat(requestBuilder.firstMatchingHeader("x-amz-decoded-content-length")).hasValue(Integer.toString(DATA.length)); assertThat(requestBuilder.firstMatchingHeader("x-amz-trailer")).hasValue("x-amz-checksum-crc32"); byte[] tmp = new byte[2048]; int actualBytes = readAll(signedPayload.newStream(), tmp); int expectedBytes = expectedByteCountUnsigned(DATA, CHUNK_SIZE); // include trailer bytes in the count: // (checksum-header + checksum-value + \r\n) expectedBytes += 21 + 8 + 2; assertThat(requestBuilder.firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue(Integer.toString(actualBytes)); assertEquals(expectedBytes, actualBytes); } @Test public void sign_shouldReturnResettableContentStreamProvider() throws IOException { AwsSigningConfig signingConfig = basicSigningConfig(); signingConfig.setSignedBodyValue(STREAMING_ECDSA_SIGNED_PAYLOAD); V4aRequestSigningResult result = new V4aRequestSigningResult( requestBuilder, "sig".getBytes(StandardCharsets.UTF_8), signingConfig ); AwsChunkedV4aPayloadSigner signer = AwsChunkedV4aPayloadSigner.builder() .credentialScope(CREDENTIAL_SCOPE) .chunkSize(CHUNK_SIZE) .build(); signer.beforeSigning(requestBuilder, PAYLOAD, signingConfig.getSignedBodyValue()); ContentStreamProvider signedPayload = signer.sign(PAYLOAD, result); assertThat(requestBuilder.firstMatchingHeader("x-amz-decoded-content-length")).hasValue(Integer.toString(DATA.length)); byte[] tmp = new byte[2048]; int expectedBytes = expectedByteCount(DATA, CHUNK_SIZE); // successive calls to newStream() should return a stream with the same data every time - this makes sure that state // isn't carried over to the new streams returned by newStream() for (int i = 0; i < 2; i++) { int actualBytes = readAll(signedPayload.newStream(), tmp); assertEquals(expectedBytes, actualBytes); } } private int readAll(InputStream src, byte[] dst) throws IOException { int read = 0; int offset = 0; while (read >= 0) { read = src.read(); if (read >= 0) { dst[offset] = (byte) read; offset += 1; } } return offset; } private AwsSigningConfig basicSigningConfig() { AwsSigningConfig signingConfig = new AwsSigningConfig(); signingConfig.setCredentials(toCredentials(AwsCredentialsIdentity.create("key", "secret"))); signingConfig.setService("s3"); signingConfig.setRegion("aws-global"); signingConfig.setAlgorithm(AwsSigningConfig.AwsSigningAlgorithm.SIGV4_ASYMMETRIC); signingConfig.setTime(Instant.now().toEpochMilli()); signingConfig.setSignatureType(AwsSigningConfig.AwsSignatureType.HTTP_REQUEST_CHUNK); return signingConfig; } private int expectedByteCount(byte[] data, int chunkSize) { int size = data.length; int ecdsaSignatureLength = 144; int chunkHeaderLength = 17 + Integer.toHexString(chunkSize).length(); int numChunks = size / chunkSize; int expectedBytes = 0; // normal chunks // x;chunk-signature=<ecdsa>\r\n<data>\r\n expectedBytes += numChunks * (chunkHeaderLength + ecdsaSignatureLength + chunkSize + 4); // remaining chunk // n;chunk-signature=<ecdsa>\r\n\<remaining-data>\r\n int remainingBytes = size % chunkSize; if (remainingBytes > 0) { int remainingChunkHeaderLength = 17 + Integer.toHexString(remainingBytes).length(); expectedBytes += remainingChunkHeaderLength + ecdsaSignatureLength + remainingBytes + 4; } // final chunk // 0;chunk-signature=<ecsda>\r\n\r\n int finalBytes = 0; int finalChunkHeaderLength = 17 + Integer.toHexString(finalBytes).length(); expectedBytes += finalChunkHeaderLength + ecdsaSignatureLength + 4; return expectedBytes; } private int expectedByteCountUnsigned(byte[] data, int chunkSize) { int size = data.length; int chunkHeaderLength = Integer.toHexString(chunkSize).length(); int numChunks = size / chunkSize; int expectedBytes = 0; // normal chunks // x\r\n<data>\r\n expectedBytes += numChunks * (chunkHeaderLength + chunkSize + 4); // remaining chunk // n\r\n\<remaining-data>\r\n int remainingBytes = size % chunkSize; if (remainingBytes > 0) { int remainingChunkHeaderLength = Integer.toHexString(remainingBytes).length(); expectedBytes += remainingChunkHeaderLength + remainingBytes + 4; } // final chunk // 0\r\n\r\n int finalBytes = 0; int finalChunkHeaderLength = Integer.toHexString(finalBytes).length(); expectedBytes += finalChunkHeaderLength + 4; return expectedBytes; } }
2,565
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/crt/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/crt/internal/signer/DefaultAwsCrtV4aHttpSignerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.signer; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static software.amazon.awssdk.checksums.DefaultChecksumAlgorithm.CRC32; import static software.amazon.awssdk.crt.auth.signing.AwsSigningConfig.AwsSignatureType.HTTP_REQUEST_VIA_HEADERS; import static software.amazon.awssdk.crt.auth.signing.AwsSigningConfig.AwsSignatureType.HTTP_REQUEST_VIA_QUERY_PARAMS; import static software.amazon.awssdk.crt.auth.signing.AwsSigningConfig.AwsSignedBodyValue.STREAMING_AWS4_ECDSA_P256_SHA256_PAYLOAD; import static software.amazon.awssdk.crt.auth.signing.AwsSigningConfig.AwsSignedBodyValue.STREAMING_AWS4_ECDSA_P256_SHA256_PAYLOAD_TRAILER; import static software.amazon.awssdk.crt.auth.signing.AwsSigningConfig.AwsSignedBodyValue.STREAMING_UNSIGNED_PAYLOAD_TRAILER; import static software.amazon.awssdk.crt.auth.signing.AwsSigningConfig.AwsSignedBodyValue.UNSIGNED_PAYLOAD; import static software.amazon.awssdk.crt.auth.signing.AwsSigningConfig.AwsSigningAlgorithm.SIGV4_ASYMMETRIC; import static software.amazon.awssdk.http.auth.aws.TestUtils.AnonymousCredentialsIdentity; import static software.amazon.awssdk.http.auth.aws.crt.TestUtils.generateBasicRequest; import static software.amazon.awssdk.http.auth.aws.crt.internal.util.CrtUtils.toCredentials; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.ChecksumUtil.readAll; import static software.amazon.awssdk.http.auth.aws.signer.AwsV4FamilyHttpSigner.CHECKSUM_ALGORITHM; import static software.amazon.awssdk.http.auth.aws.signer.AwsV4aHttpSigner.AUTH_LOCATION; import static software.amazon.awssdk.http.auth.aws.signer.AwsV4aHttpSigner.AuthLocation; import static software.amazon.awssdk.http.auth.aws.signer.AwsV4aHttpSigner.CHUNK_ENCODING_ENABLED; import static software.amazon.awssdk.http.auth.aws.signer.AwsV4aHttpSigner.EXPIRATION_DURATION; import static software.amazon.awssdk.http.auth.aws.signer.AwsV4aHttpSigner.PAYLOAD_SIGNING_ENABLED; import java.time.Duration; import org.junit.jupiter.api.Test; import software.amazon.awssdk.crt.auth.signing.AwsSigningConfig; import software.amazon.awssdk.http.Header; import software.amazon.awssdk.http.auth.spi.signer.AsyncSignRequest; import software.amazon.awssdk.http.auth.spi.signer.SignRequest; import software.amazon.awssdk.http.auth.spi.signer.SignedRequest; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; /** * Functional tests for the Sigv4a signer. These tests call the CRT native signer code. */ public class DefaultAwsCrtV4aHttpSignerTest { DefaultAwsCrtV4aHttpSigner signer = new DefaultAwsCrtV4aHttpSigner(); @Test public void sign_withBasicRequest_shouldSignWithHeaders() { AwsCredentialsIdentity credentials = AwsCredentialsIdentity.create("AKIDEXAMPLE", "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY"); SignRequest<AwsCredentialsIdentity> request = generateBasicRequest( credentials, httpRequest -> httpRequest.port(443), signRequest -> { } ); AwsSigningConfig expectedSigningConfig = new AwsSigningConfig(); expectedSigningConfig.setCredentials(toCredentials(request.identity())); expectedSigningConfig.setService("demo"); expectedSigningConfig.setRegion("aws-global"); expectedSigningConfig.setAlgorithm(SIGV4_ASYMMETRIC); expectedSigningConfig.setTime(1596476903000L); expectedSigningConfig.setUseDoubleUriEncode(true); expectedSigningConfig.setShouldNormalizeUriPath(true); expectedSigningConfig.setSignatureType(HTTP_REQUEST_VIA_HEADERS); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingHeader("Host")).hasValue("demo.us-east-1.amazonaws.com"); assertThat(signedRequest.request().firstMatchingHeader("X-Amz-Date")).hasValue("20200803T174823Z"); assertThat(signedRequest.request().firstMatchingHeader("X-Amz-Region-Set")).hasValue("aws-global"); assertThat(signedRequest.request().firstMatchingHeader("Authorization")).isPresent(); } @Test public void sign_withQuery_shouldSignWithQueryParams() { AwsCredentialsIdentity credentials = AwsCredentialsIdentity.create("AKIDEXAMPLE", "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY"); SignRequest<AwsCredentialsIdentity> request = generateBasicRequest( credentials, httpRequest -> httpRequest.port(443), signRequest -> signRequest.putProperty(AUTH_LOCATION, AuthLocation.QUERY_STRING) ); AwsSigningConfig expectedSigningConfig = new AwsSigningConfig(); expectedSigningConfig.setCredentials(toCredentials(request.identity())); expectedSigningConfig.setService("demo"); expectedSigningConfig.setRegion("aws-global"); expectedSigningConfig.setAlgorithm(SIGV4_ASYMMETRIC); expectedSigningConfig.setTime(1596476903000L); expectedSigningConfig.setUseDoubleUriEncode(true); expectedSigningConfig.setShouldNormalizeUriPath(true); expectedSigningConfig.setSignatureType(HTTP_REQUEST_VIA_QUERY_PARAMS); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingRawQueryParameter("X-Amz-Algorithm")) .hasValue("AWS4-ECDSA-P256-SHA256"); assertThat(signedRequest.request().firstMatchingRawQueryParameter("X-Amz-Credential")) .hasValue("AKIDEXAMPLE/20200803/demo/aws4_request"); assertThat(signedRequest.request().firstMatchingRawQueryParameter("X-Amz-Date")).hasValue("20200803T174823Z"); assertThat(signedRequest.request().firstMatchingRawQueryParameter("X-Amz-SignedHeaders")) .hasValue("host;x-amz-archive-description"); assertThat(signedRequest.request().firstMatchingRawQueryParameter("X-Amz-Region-Set")).hasValue("aws-global"); assertThat(signedRequest.request().firstMatchingRawQueryParameter("X-Amz-Signature")).isPresent(); } @Test public void sign_withQueryAndExpiration_shouldSignWithQueryParamsAndExpire() { AwsCredentialsIdentity credentials = AwsCredentialsIdentity.create("AKIDEXAMPLE", "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY"); SignRequest<AwsCredentialsIdentity> request = generateBasicRequest( credentials, httpRequest -> httpRequest.port(443), signRequest -> signRequest .putProperty(AUTH_LOCATION, AuthLocation.QUERY_STRING) .putProperty(EXPIRATION_DURATION, Duration.ofSeconds(1)) ); AwsSigningConfig expectedSigningConfig = new AwsSigningConfig(); expectedSigningConfig.setCredentials(toCredentials(request.identity())); expectedSigningConfig.setService("demo"); expectedSigningConfig.setRegion("aws-global"); expectedSigningConfig.setAlgorithm(SIGV4_ASYMMETRIC); expectedSigningConfig.setTime(1596476903000L); expectedSigningConfig.setUseDoubleUriEncode(true); expectedSigningConfig.setShouldNormalizeUriPath(true); expectedSigningConfig.setSignatureType(HTTP_REQUEST_VIA_QUERY_PARAMS); expectedSigningConfig.setExpirationInSeconds(1); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingRawQueryParameter("X-Amz-Algorithm")) .hasValue("AWS4-ECDSA-P256-SHA256"); assertThat(signedRequest.request().firstMatchingRawQueryParameter("X-Amz-Credential")) .hasValue("AKIDEXAMPLE/20200803/demo/aws4_request"); assertThat(signedRequest.request().firstMatchingRawQueryParameter("X-Amz-Date")).hasValue("20200803T174823Z"); assertThat(signedRequest.request().firstMatchingRawQueryParameter("X-Amz-SignedHeaders")) .hasValue("host;x-amz-archive-description"); assertThat(signedRequest.request().firstMatchingRawQueryParameter("X-Amz-Region-Set")).hasValue("aws-global"); assertThat(signedRequest.request().firstMatchingRawQueryParameter("X-Amz-Signature")).isPresent(); assertThat(signedRequest.request().firstMatchingRawQueryParameter("X-Amz-Expires")).hasValue("1"); } @Test public void sign_withUnsignedPayload_shouldNotSignPayload() { AwsCredentialsIdentity credentials = AwsCredentialsIdentity.create("AKIDEXAMPLE", "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY"); SignRequest<AwsCredentialsIdentity> request = generateBasicRequest( credentials, httpRequest -> { }, signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, false) ); AwsSigningConfig expectedSigningConfig = new AwsSigningConfig(); expectedSigningConfig.setCredentials(toCredentials(request.identity())); expectedSigningConfig.setService("demo"); expectedSigningConfig.setRegion("aws-global"); expectedSigningConfig.setAlgorithm(SIGV4_ASYMMETRIC); expectedSigningConfig.setTime(1596476903000L); expectedSigningConfig.setUseDoubleUriEncode(true); expectedSigningConfig.setShouldNormalizeUriPath(true); expectedSigningConfig.setSignatureType(HTTP_REQUEST_VIA_HEADERS); expectedSigningConfig.setSignedBodyValue(UNSIGNED_PAYLOAD); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingHeader("Host")).hasValue("demo.us-east-1.amazonaws.com"); assertThat(signedRequest.request().firstMatchingHeader("X-Amz-Date")).hasValue("20200803T174823Z"); assertThat(signedRequest.request().firstMatchingHeader("X-Amz-Region-Set")).hasValue("aws-global"); assertThat(signedRequest.request().firstMatchingHeader("Authorization")).isPresent(); } @Test public void sign_withAnonymousCredentials_shouldNotSign() { AwsCredentialsIdentity credentials = new AnonymousCredentialsIdentity(); SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( credentials, httpRequest -> { }, signRequest -> { } ); SignedRequest signedRequest = signer.sign(request); assertNull(signedRequest.request().headers().get("Authorization")); } @Test public void signAsync_throwsUnsupportedOperationException() { assertThrows(UnsupportedOperationException.class, () -> signer.signAsync((AsyncSignRequest<? extends AwsCredentialsIdentity>) null) ); } @Test public void sign_WithChunkEncodingTrue_DelegatesToAwsChunkedPayloadSigner() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader(Header.CONTENT_LENGTH, "20"), signRequest -> signRequest .putProperty(CHUNK_ENCODING_ENABLED, true) ); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")) .hasValue(STREAMING_AWS4_ECDSA_P256_SHA256_PAYLOAD); assertThat(signedRequest.request().firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue("353"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-decoded-content-length")).hasValue("20"); // Ensures that CRT runs correctly and without throwing an exception readAll(signedRequest.payload().get().newStream()); } @Test public void sign_WithChunkEncodingTrueAndChecksumAlgorithm_DelegatesToAwsChunkedPayloadSigner() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader(Header.CONTENT_LENGTH, "20"), signRequest -> signRequest .putProperty(CHUNK_ENCODING_ENABLED, true) .putProperty(CHECKSUM_ALGORITHM, CRC32) ); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")) .hasValue(STREAMING_AWS4_ECDSA_P256_SHA256_PAYLOAD_TRAILER); assertThat(signedRequest.request().firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue("554"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-decoded-content-length")).hasValue("20"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-trailer")).hasValue("x-amz-checksum-crc32"); // Ensures that CRT runs correctly and without throwing an exception readAll(signedRequest.payload().get().newStream()); } @Test public void sign_WithPayloadSigningFalseAndChunkEncodingTrueAndTrailer_DelegatesToAwsChunkedPayloadSigner() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader(Header.CONTENT_LENGTH, "20"), signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, false) .putProperty(CHUNK_ENCODING_ENABLED, true) .putProperty(CHECKSUM_ALGORITHM, CRC32) ); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")) .hasValue(STREAMING_UNSIGNED_PAYLOAD_TRAILER); assertThat(signedRequest.request().firstMatchingHeader(Header.CONTENT_LENGTH)).hasValue("62"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-decoded-content-length")).hasValue("20"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-trailer")).hasValue("x-amz-checksum-crc32"); // Ensures that CRT runs correctly and without throwing an exception readAll(signedRequest.payload().get().newStream()); } @Test public void sign_WithPayloadSigningFalseAndChunkEncodingTrueWithoutTrailer_DelegatesToUnsignedPayload() { SignRequest<? extends AwsCredentialsIdentity> request = generateBasicRequest( AwsCredentialsIdentity.create("access", "secret"), httpRequest -> httpRequest .putHeader(Header.CONTENT_LENGTH, "20"), signRequest -> signRequest .putProperty(PAYLOAD_SIGNING_ENABLED, false) .putProperty(CHUNK_ENCODING_ENABLED, true) ); SignedRequest signedRequest = signer.sign(request); assertThat(signedRequest.request().firstMatchingHeader("x-amz-content-sha256")).hasValue("UNSIGNED-PAYLOAD"); assertThat(signedRequest.request().firstMatchingHeader("x-amz-decoded-content-length")).isNotPresent(); } }
2,566
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/crt/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/test/java/software/amazon/awssdk/http/auth/aws/crt/internal/util/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.http.auth.aws.crt.internal.util; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.http.auth.aws.crt.internal.util.CrtHttpRequestConverter.toCrtStream; import static software.amazon.awssdk.http.auth.aws.crt.internal.util.CrtHttpRequestConverter.toRequest; 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.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.ContentStreamProvider; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.utils.BinaryUtils; public class CrtHttpRequestConverterTest { @Test public void request_withHeaders_isConvertedToCrtFormat() { String data = "data"; SdkHttpRequest request = SdkHttpFullRequest.builder() .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")) .build(); ContentStreamProvider payload = () -> new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); HttpRequest crtHttpRequest = toRequest(request, payload); 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() { SdkHttpRequest 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 = toRequest(request, (ContentStreamProvider) null); assertThat(crtHttpRequest.getMethod()).isEqualTo("GET"); assertThat(crtHttpRequest.getEncodedPath()).isEqualTo("/path?param1=value1&param2=value2-1&param2=value2-2"); assertHttpRequestSame(request, crtHttpRequest); } @Test public void request_withEmptyPath_isConvertedToCrtFormat() { SdkHttpFullRequest request = SdkHttpFullRequest.builder() .method(SdkHttpMethod.GET) .putHeader("Host", "demo.us-east-1.amazonaws.com") .encodedPath("") .uri(URI.create("https://demo.us-east-1.amazonaws.com")) .build(); HttpRequest crtHttpRequest = toRequest(request, (ContentStreamProvider) null); 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 = 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(SdkHttpRequest originalRequest, HttpRequest crtRequest) { SdkHttpRequest sdkRequest = toRequest(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); } }
2,567
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/scheme/AwsV4aAuthScheme.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.scheme; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.http.auth.aws.internal.scheme.DefaultAwsV4aAuthScheme; import software.amazon.awssdk.http.auth.aws.signer.AwsV4aHttpSigner; import software.amazon.awssdk.http.auth.spi.scheme.AuthScheme; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.identity.spi.IdentityProviders; /** * The <a href="https://smithy.io/2.0/aws/aws-auth.html#aws-auth-sigv4a-trait">aws.auth#sigv4a</a> auth scheme, which uses a * {@link AwsCredentialsIdentity} and AwsV4aHttpSigner. */ @SdkPublicApi public interface AwsV4aAuthScheme extends AuthScheme<AwsCredentialsIdentity> { /** * The scheme ID for this interface. */ String SCHEME_ID = "aws.auth#sigv4a"; /** * Get a default implementation of a {@link AwsV4aAuthScheme} */ static AwsV4aAuthScheme create() { return DefaultAwsV4aAuthScheme.create(); } /** * Retrieve the {@link AwsCredentialsIdentity} based {@link IdentityProvider} associated with this authentication scheme. */ @Override IdentityProvider<AwsCredentialsIdentity> identityProvider(IdentityProviders providers); /** * Retrieve the {@link AwsV4aHttpSigner} associated with this authentication scheme. */ @Override AwsV4aHttpSigner signer(); }
2,568
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/scheme/AwsV4AuthScheme.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.scheme; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.http.auth.aws.internal.scheme.DefaultAwsV4AuthScheme; import software.amazon.awssdk.http.auth.aws.signer.AwsV4HttpSigner; import software.amazon.awssdk.http.auth.spi.scheme.AuthScheme; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.identity.spi.IdentityProviders; /** * The <a href="https://smithy.io/2.0/aws/aws-auth.html#aws-auth-sigv4-trait">aws.auth#sigv4</a> auth scheme, which uses a * {@link AwsCredentialsIdentity} and {@link AwsV4HttpSigner}. */ @SdkPublicApi public interface AwsV4AuthScheme extends AuthScheme<AwsCredentialsIdentity> { /** * The scheme ID for this interface. */ String SCHEME_ID = "aws.auth#sigv4"; /** * Get a default implementation of a {@link AwsV4AuthScheme} */ static AwsV4AuthScheme create() { return DefaultAwsV4AuthScheme.create(); } /** * Retrieve the {@link AwsCredentialsIdentity} based {@link IdentityProvider} associated with this authentication scheme. */ @Override IdentityProvider<AwsCredentialsIdentity> identityProvider(IdentityProviders providers); /** * Retrieve the {@link AwsV4HttpSigner} associated with this authentication scheme. */ @Override AwsV4HttpSigner signer(); }
2,569
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/signer/AwsV4HttpSigner.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.signer; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.http.auth.aws.internal.signer.DefaultAwsV4HttpSigner; import software.amazon.awssdk.http.auth.spi.signer.HttpSigner; import software.amazon.awssdk.http.auth.spi.signer.SignerProperty; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; /** * An {@link HttpSigner} that will sign a request using an AWS credentials {@link AwsCredentialsIdentity}). * <p> * The process for signing requests to send to AWS services is documented * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html">here</a>. */ @SdkPublicApi public interface AwsV4HttpSigner extends AwsV4FamilyHttpSigner<AwsCredentialsIdentity> { /** * The AWS region name to be used for computing the signature. This property is required. */ SignerProperty<String> REGION_NAME = SignerProperty.create(AwsV4HttpSigner.class, "RegionName"); /** * Get a default implementation of a {@link AwsV4HttpSigner} */ static AwsV4HttpSigner create() { return new DefaultAwsV4HttpSigner(); } }
2,570
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/signer/RegionSet.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.signer; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.utils.Validate; /** * This class represents the concept of a set of regions. * <p> * A region-set can contain one or more comma-separated AWS regions, or a single wildcard to represent all regions ("global"). * Whitespace is trimmed from entries of the set. * <p> * Examples of region-sets: * <ul> * <li>'*' - Represents all regions, global</li> * <li>'eu-west-1' - Represents a single region, eu-west-1</li> * <li>'us-west-2,us-east-1' - Represents 2 regions, us-west-2 and us-east-1</li> * </ul> */ @SdkPublicApi @Immutable public final class RegionSet { /** * The "Global" region, which is represented with a single wildcard character: "*". */ public static final RegionSet GLOBAL; static { GLOBAL = create(Collections.singleton("*")); } private final Set<String> regionSet; private final String regionSetString; private RegionSet(Collection<String> regions) { this.regionSet = Collections.unmodifiableSet(new HashSet<>(regions)); this.regionSetString = String.join(",", regionSet); } /** * Gets the string representation of this RegionSet. */ public String asString() { return regionSetString; } /** * Gets the set of strings that represent this RegionSet. */ public Set<String> asSet() { return regionSet; } /** * Creates a RegionSet with the supplied region-set string. * * @param value See class documentation {@link RegionSet} for the expected format. */ public static RegionSet create(String value) { Validate.notBlank(value, "value must not be blank!"); return create(Arrays.asList(value.trim().split(","))); } /** * Creates a RegionSet from the supplied collection. * * @param regions A collection of regions. */ public static RegionSet create(Collection<String> regions) { Validate.notEmpty(regions, "regions must not be empty!"); return new RegionSet( regions.stream().map(s -> Validate.notBlank(s, "region must not be empty!").trim()).collect(Collectors.toList()) ); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RegionSet that = (RegionSet) o; return regionSet.equals(that.regionSet); } @Override public int hashCode() { return Objects.hashCode(regionSet); } }
2,571
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/signer/AwsV4aHttpSigner.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.signer; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.OptionalDependencyLoaderUtil.getDefaultAwsCrtV4aHttpSigner; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.http.auth.spi.signer.HttpSigner; import software.amazon.awssdk.http.auth.spi.signer.SignerProperty; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; /** * An {@link HttpSigner} that will sign a request using an AWS credentials {@link AwsCredentialsIdentity}). * <p> * The process for signing requests to send to AWS services is documented * <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html">here</a>. */ @SdkPublicApi public interface AwsV4aHttpSigner extends AwsV4FamilyHttpSigner<AwsCredentialsIdentity> { /** * The AWS region-set to be used for computing the signature. This property is required. */ SignerProperty<RegionSet> REGION_SET = SignerProperty.create(AwsV4aHttpSigner.class, "RegionSet"); /** * Get a default implementation of a {@link AwsV4aHttpSigner} */ static AwsV4aHttpSigner create() { return getDefaultAwsCrtV4aHttpSigner(); } }
2,572
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/signer/AwsV4FamilyHttpSigner.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.signer; import java.time.Duration; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.checksums.spi.ChecksumAlgorithm; import software.amazon.awssdk.http.auth.spi.signer.HttpSigner; import software.amazon.awssdk.http.auth.spi.signer.SignerProperty; import software.amazon.awssdk.identity.spi.Identity; /** * An interface shared by {@link AwsV4HttpSigner} and {@link AwsV4aHttpSigner} for defining signer properties that are common * across both signers. */ @SdkPublicApi public interface AwsV4FamilyHttpSigner<T extends Identity> extends HttpSigner<T> { /** * The name of the AWS service. This property is required. */ SignerProperty<String> SERVICE_SIGNING_NAME = SignerProperty.create(AwsV4FamilyHttpSigner.class, "ServiceSigningName"); /** * A boolean to indicate whether to double url-encode the resource path when constructing the canonical request. This property * defaults to true. */ SignerProperty<Boolean> DOUBLE_URL_ENCODE = SignerProperty.create(AwsV4FamilyHttpSigner.class, "DoubleUrlEncode"); /** * A boolean to indicate whether the resource path should be "normalized" according to RFC3986 when constructing the canonical * request. This property defaults to true. */ SignerProperty<Boolean> NORMALIZE_PATH = SignerProperty.create(AwsV4FamilyHttpSigner.class, "NormalizePath"); /** * The location where auth-related data is inserted, as a result of signing. This property defaults to HEADER. */ SignerProperty<AuthLocation> AUTH_LOCATION = SignerProperty.create(AwsV4FamilyHttpSigner.class, "AuthLocation"); /** * The duration for the request to be valid. This property defaults to null. This can be set to presign the request for * later use. The maximum allowed value for this property is 7 days. This is only supported when AuthLocation=QUERY. */ SignerProperty<Duration> EXPIRATION_DURATION = SignerProperty.create(AwsV4FamilyHttpSigner.class, "ExpirationDuration"); /** * Whether to indicate that a payload is signed or not. This property defaults to true. This can be set false to disable * payload signing. */ SignerProperty<Boolean> PAYLOAD_SIGNING_ENABLED = SignerProperty.create(AwsV4FamilyHttpSigner.class, "PayloadSigningEnabled"); /** * Whether to indicate that a payload is chunk-encoded or not. This property defaults to false. This can be set true to * enable the `aws-chunk` content-encoding */ SignerProperty<Boolean> CHUNK_ENCODING_ENABLED = SignerProperty.create(AwsV4FamilyHttpSigner.class, "ChunkEncodingEnabled"); /** * The algorithm to use for calculating a "flexible" checksum. This property is optional. */ SignerProperty<ChecksumAlgorithm> CHECKSUM_ALGORITHM = SignerProperty.create(AwsV4FamilyHttpSigner.class, "ChecksumAlgorithm"); /** * This enum represents where auth-related data is inserted, as a result of signing. */ enum AuthLocation { /** * Indicates auth-related data is inserted in HTTP headers. */ HEADER, /** * Indicates auth-related data is inserted in HTTP query-parameters. */ QUERY_STRING } }
2,573
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/eventstream/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/eventstream/internal/signer/EventStreamV4PayloadSigner.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.eventstream.internal.signer; import java.nio.ByteBuffer; import java.time.Clock; import org.reactivestreams.Publisher; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.ContentStreamProvider; import software.amazon.awssdk.http.auth.aws.eventstream.internal.io.SigV4DataFramePublisher; import software.amazon.awssdk.http.auth.aws.internal.signer.CredentialScope; import software.amazon.awssdk.http.auth.aws.internal.signer.V4PayloadSigner; import software.amazon.awssdk.http.auth.aws.internal.signer.V4RequestSigningResult; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.utils.Validate; /** * An implementation which supports async signing of event-stream payloads. */ @SdkInternalApi public class EventStreamV4PayloadSigner implements V4PayloadSigner { private final AwsCredentialsIdentity credentials; private final CredentialScope credentialScope; private final Clock signingClock; public EventStreamV4PayloadSigner(Builder builder) { this.credentials = Validate.paramNotNull(builder.credentials, "Credentials"); this.credentialScope = Validate.paramNotNull(builder.credentialScope, "CredentialScope"); this.signingClock = Validate.paramNotNull(builder.signingClock, "SigningClock"); } public static Builder builder() { return new Builder(); } @Override public ContentStreamProvider sign(ContentStreamProvider payload, V4RequestSigningResult requestSigningResult) { throw new UnsupportedOperationException(); } @Override public Publisher<ByteBuffer> signAsync(Publisher<ByteBuffer> payload, V4RequestSigningResult requestSigningResult) { return SigV4DataFramePublisher.builder() .publisher(payload) .credentials(credentials) .credentialScope(credentialScope) .signature(requestSigningResult.getSignature()) .signingClock(signingClock) .build(); } public static class Builder { private AwsCredentialsIdentity credentials; private CredentialScope credentialScope; private Clock signingClock; public Builder credentials(AwsCredentialsIdentity credentials) { this.credentials = credentials; return this; } public Builder credentialScope(CredentialScope credentialScope) { this.credentialScope = credentialScope; return this; } public Builder signingClock(Clock signingClock) { this.signingClock = signingClock; return this; } public EventStreamV4PayloadSigner build() { return new EventStreamV4PayloadSigner(this); } } }
2,574
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/eventstream/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/eventstream/internal/io/TrailingDataFramePublisher.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.eventstream.internal.io; import java.nio.ByteBuffer; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkInternalApi; /** * A publisher which wraps a publisher and appends a trailing frame once the wrapped publisher is finished. */ @SdkInternalApi public final class TrailingDataFramePublisher implements Publisher<ByteBuffer> { private final Publisher<ByteBuffer> trailingPublisher; public TrailingDataFramePublisher(Publisher<ByteBuffer> publisher) { this.trailingPublisher = subscriber -> { Subscriber<ByteBuffer> adaptedSubscriber = new SubscriberAdapter(subscriber); publisher.subscribe(adaptedSubscriber); }; } @Override public void subscribe(Subscriber<? super ByteBuffer> subscriber) { trailingPublisher.subscribe(subscriber); } static class SubscriberAdapter implements Subscriber<ByteBuffer> { private final AtomicBoolean upstreamDone = new AtomicBoolean(false); private final AtomicLong downstreamDemand = new AtomicLong(); private final Object lock = new Object(); private final Subscriber<? super ByteBuffer> delegate; private volatile boolean sentTrailingFrame = false; SubscriberAdapter(Subscriber<? super ByteBuffer> actual) { this.delegate = actual; } @Override public void onSubscribe(Subscription s) { delegate.onSubscribe(new Subscription() { @Override public void request(long n) { if (n <= 0) { onError(new IllegalArgumentException("n > 0 required but it was " + n)); } downstreamDemand.getAndAdd(n); if (upstreamDone.get()) { sendTrailingEmptyFrame(); } else { s.request(n); } } @Override public void cancel() { s.cancel(); } }); } @Override public void onNext(ByteBuffer byteBuffer) { downstreamDemand.decrementAndGet(); delegate.onNext(byteBuffer); } @Override public void onError(Throwable t) { upstreamDone.compareAndSet(false, true); delegate.onError(t); } @Override public void onComplete() { upstreamDone.compareAndSet(false, true); if (downstreamDemand.get() > 0) { sendTrailingEmptyFrame(); } } private void sendTrailingEmptyFrame() { // when upstream complete, send a trailing empty frame synchronized (lock) { if (!sentTrailingFrame) { sentTrailingFrame = true; delegate.onNext(ByteBuffer.wrap(new byte[] {})); delegate.onComplete(); } } } } }
2,575
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/eventstream/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/eventstream/internal/io/SigV4DataFramePublisher.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.eventstream.internal.io; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerUtils.computeSignature; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerUtils.deriveSigningKey; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerUtils.hash; import java.nio.ByteBuffer; import java.time.Clock; import java.time.Instant; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; import java.util.function.Function; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.auth.aws.internal.signer.CredentialScope; import software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerConstant; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.utils.BinaryUtils; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.internal.MappingSubscriber; import software.amazon.eventstream.HeaderValue; import software.amazon.eventstream.Message; /** * A publisher which adapts a publisher by SigV4-signing each frame, and appends an empty trailing frame. */ @SdkInternalApi public final class SigV4DataFramePublisher implements Publisher<ByteBuffer> { private static final Logger LOG = Logger.loggerFor(SigV4DataFramePublisher.class); private static final String CHUNK_SIGNATURE = ":chunk-signature"; private static final int PAYLOAD_TRUNCATE_LENGTH = 32; private final Publisher<ByteBuffer> sigv4Publisher; private SigV4DataFramePublisher(Builder builder) { Validate.paramNotNull(builder.publisher, "Publisher"); Validate.paramNotNull(builder.credentials, "Credentials"); Validate.paramNotNull(builder.credentialScope, "CredentialScope"); Validate.paramNotNull(builder.signature, "Signature"); Validate.paramNotNull(builder.signingClock, "SigningClock"); // Adapt the publisher with a trailing-empty frame publisher Publisher<ByteBuffer> trailingPublisher = new TrailingDataFramePublisher(builder.publisher); // Map publisher with signing function this.sigv4Publisher = subscriber -> { Subscriber<ByteBuffer> adaptedSubscriber = MappingSubscriber.create(subscriber, getDataFrameSigner(builder.credentials, builder.credentialScope, builder.signature, builder.signingClock ) ); trailingPublisher.subscribe(adaptedSubscriber); }; } private static Function<ByteBuffer, ByteBuffer> getDataFrameSigner(AwsCredentialsIdentity credentials, CredentialScope credentialScope, String signature, Clock signingClock) { return new Function<ByteBuffer, ByteBuffer>() { /** * Initiate rolling signature with an initial signature */ String priorSignature = signature; @Override public ByteBuffer apply(ByteBuffer byteBuffer) { /** * Signing Date */ Map<String, HeaderValue> eventHeaders = new HashMap<>(); Instant signingInstant = signingClock.instant(); eventHeaders.put(":date", HeaderValue.fromTimestamp(signingInstant)); /** * Derive Signing Key - since a stream of events could be over a period of time, we should update * the credential scope with the new instant every time the data-frame signer is called */ CredentialScope updatedCredentialScope = new CredentialScope(credentialScope.getRegion(), credentialScope.getService(), signingInstant); byte[] signingKey = deriveSigningKey(credentials, updatedCredentialScope); /** * Calculate rolling signature */ byte[] payload = new byte[byteBuffer.remaining()]; byteBuffer.get(payload); byte[] signatureBytes = signEvent(priorSignature, signingKey, updatedCredentialScope, eventHeaders, payload); priorSignature = BinaryUtils.toHex(signatureBytes); /** * Add signing layer headers */ Map<String, HeaderValue> headers = new HashMap<>(eventHeaders); //Signature headers headers.put(CHUNK_SIGNATURE, HeaderValue.fromByteArray(signatureBytes)); /** * Wrap payload and headers in a Message object and then encode to bytes */ Message signedMessage = new Message(sortHeaders(headers), payload); if (LOG.isLoggingLevelEnabled("trace")) { LOG.trace(() -> "Signed message: " + toDebugString(signedMessage, false)); } else { LOG.debug(() -> "Signed message: " + toDebugString(signedMessage, true)); } return signedMessage.toByteBuffer(); } }; } /** * Sign an event/chunk via SigV4 * * @param priorSignature signature of previous frame * @param signingKey derived signing key * @param credentialScope the credential-scope used to provide region, service, and time * @param eventHeaders headers pertinent to the event * @param event an event of a bytes to sign * @return encoded event with signature */ private static byte[] signEvent( String priorSignature, byte[] signingKey, CredentialScope credentialScope, Map<String, HeaderValue> eventHeaders, byte[] event) { // String to sign String eventHeadersSignature = BinaryUtils.toHex(hash(Message.encodeHeaders(sortHeaders(eventHeaders).entrySet()))); String eventHash = BinaryUtils.toHex(hash(event)); String stringToSign = "AWS4-HMAC-SHA256-PAYLOAD" + SignerConstant.LINE_SEPARATOR + credentialScope.getDatetime() + SignerConstant.LINE_SEPARATOR + credentialScope.scope() + SignerConstant.LINE_SEPARATOR + priorSignature + SignerConstant.LINE_SEPARATOR + eventHeadersSignature + SignerConstant.LINE_SEPARATOR + eventHash; // calculate signature return computeSignature(stringToSign, signingKey); } /** * Sort event headers in alphabetic order, with exception that CHUNK_SIGNATURE header always at last * * @param headers unsorted event headers * @return sorted event headers */ private static TreeMap<String, HeaderValue> sortHeaders(Map<String, HeaderValue> headers) { TreeMap<String, HeaderValue> sortedHeaders = new TreeMap<>((header1, header2) -> { // CHUNK_SIGNATURE should always be the last header if (header1.equals(CHUNK_SIGNATURE)) { return 1; // put header1 at last } if (header2.equals(CHUNK_SIGNATURE)) { return -1; // put header2 at last } return header1.compareTo(header2); }); sortedHeaders.putAll(headers); return sortedHeaders; } private static String toDebugString(Message m, boolean truncatePayload) { StringBuilder sb = new StringBuilder("Message = {headers={"); Map<String, HeaderValue> headers = m.getHeaders(); Iterator<Map.Entry<String, HeaderValue>> headersIter = headers.entrySet().iterator(); while (headersIter.hasNext()) { Map.Entry<String, HeaderValue> h = headersIter.next(); sb.append(h.getKey()).append("={").append(h.getValue().toString()).append("}"); if (headersIter.hasNext()) { sb.append(", "); } } sb.append("}, payload="); byte[] payload = m.getPayload(); byte[] payloadToLog; // We don't actually need to truncate if the payload length is already within the truncate limit truncatePayload = truncatePayload && payload.length > PAYLOAD_TRUNCATE_LENGTH; if (truncatePayload) { // Would be nice if BinaryUtils.toHex() could take an array index range instead, so we don't need to copy payloadToLog = Arrays.copyOf(payload, PAYLOAD_TRUNCATE_LENGTH); } else { payloadToLog = payload; } sb.append(BinaryUtils.toHex(payloadToLog)); if (truncatePayload) { sb.append("..."); } sb.append("}"); return sb.toString(); } public static Builder builder() { return new Builder(); } @Override public void subscribe(Subscriber<? super ByteBuffer> subscriber) { sigv4Publisher.subscribe(subscriber); } public static class Builder { private Publisher<ByteBuffer> publisher; private AwsCredentialsIdentity credentials; private CredentialScope credentialScope; private String signature; private Clock signingClock; public Builder publisher(Publisher<ByteBuffer> publisher) { this.publisher = publisher; return this; } public Builder credentials(AwsCredentialsIdentity credentials) { this.credentials = credentials; return this; } public Builder credentialScope(CredentialScope credentialScope) { this.credentialScope = credentialScope; return this; } public Builder signature(String signature) { this.signature = signature; return this; } public Builder signingClock(Clock signingClock) { this.signingClock = signingClock; return this; } public SigV4DataFramePublisher build() { return new SigV4DataFramePublisher(this); } } }
2,576
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal/scheme/DefaultAwsV4aAuthScheme.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.scheme; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.auth.aws.scheme.AwsV4aAuthScheme; import software.amazon.awssdk.http.auth.aws.signer.AwsV4aHttpSigner; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.identity.spi.IdentityProviders; /** * A default implementation of {@link AwsV4aAuthScheme}. */ @SdkInternalApi public final class DefaultAwsV4aAuthScheme implements AwsV4aAuthScheme { private static final DefaultAwsV4aAuthScheme DEFAULT = new DefaultAwsV4aAuthScheme(); /** * Returns an instance of the {@link DefaultAwsV4aAuthScheme}. */ public static DefaultAwsV4aAuthScheme create() { return DEFAULT; } @Override public String schemeId() { return SCHEME_ID; } @Override public IdentityProvider<AwsCredentialsIdentity> identityProvider(IdentityProviders providers) { return providers.identityProvider(AwsCredentialsIdentity.class); } /** * AwsV4aHttpSigner.create() returns the CRT implementation and requires the optional dependency http-auth-aws-crt to be * added. So lazily creating the instance only when this method is called. */ @Override public AwsV4aHttpSigner signer() { return SignerSingletonHolder.INSTANCE; } private static class SignerSingletonHolder { private static final AwsV4aHttpSigner INSTANCE = AwsV4aHttpSigner.create(); } }
2,577
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal/scheme/DefaultAwsV4AuthScheme.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.scheme; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.auth.aws.scheme.AwsV4AuthScheme; import software.amazon.awssdk.http.auth.aws.signer.AwsV4HttpSigner; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.identity.spi.IdentityProviders; /** * A default implementation of {@link AwsV4AuthScheme}. */ @SdkInternalApi public final class DefaultAwsV4AuthScheme implements AwsV4AuthScheme { private static final DefaultAwsV4AuthScheme DEFAULT = new DefaultAwsV4AuthScheme(); private static final AwsV4HttpSigner DEFAULT_SIGNER = AwsV4HttpSigner.create(); /** * Returns an instance of the {@link DefaultAwsV4AuthScheme}. */ public static DefaultAwsV4AuthScheme create() { return DEFAULT; } @Override public String schemeId() { return SCHEME_ID; } @Override public IdentityProvider<AwsCredentialsIdentity> identityProvider(IdentityProviders providers) { return providers.identityProvider(AwsCredentialsIdentity.class); } @Override public AwsV4HttpSigner signer() { return DEFAULT_SIGNER; } }
2,578
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal/signer/PrecomputedSha256Checksummer.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.signer; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerConstant.X_AMZ_CONTENT_SHA256; import java.nio.ByteBuffer; import java.util.concurrent.Callable; import java.util.concurrent.CompletableFuture; import org.reactivestreams.Publisher; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.ContentStreamProvider; import software.amazon.awssdk.http.SdkHttpRequest; /** * An implementation of a checksummer that simply passes along a computed value as a checksum. Specifically, this is used in the * cases where the checksum is a pre-defined value that dictates specific behavior by the signer, and flexible checksums is not * enabled for the request (such as aws-chunked payload signing without trailers, unsigned streaming without trailers, etc.). */ @SdkInternalApi public final class PrecomputedSha256Checksummer implements Checksummer { private final Callable<String> computation; public PrecomputedSha256Checksummer(Callable<String> computation) { this.computation = computation; } @Override public void checksum(ContentStreamProvider payload, SdkHttpRequest.Builder request) { try { String checksum = computation.call(); request.putHeader(X_AMZ_CONTENT_SHA256, checksum); } catch (Exception e) { throw new RuntimeException("Could not retrieve checksum: ", e); } } @Override public CompletableFuture<Publisher<ByteBuffer>> checksum(Publisher<ByteBuffer> payload, SdkHttpRequest.Builder request) { try { String checksum = computation.call(); request.putHeader(X_AMZ_CONTENT_SHA256, checksum); return CompletableFuture.completedFuture(payload); } catch (Exception e) { throw new RuntimeException("Could not retrieve checksum: ", e); } } }
2,579
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal/signer/V4RequestSigner.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.signer; import static software.amazon.awssdk.http.auth.aws.internal.signer.V4CanonicalRequest.getCanonicalHeaders; import static software.amazon.awssdk.http.auth.aws.internal.signer.V4CanonicalRequest.getSignedHeadersString; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerConstant.AWS4_SIGNING_ALGORITHM; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerConstant.X_AMZ_CONTENT_SHA256; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerUtils.addDateHeader; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerUtils.addHostHeader; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerUtils.formatDateTime; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerUtils.getContentHash; import java.time.Duration; import java.util.List; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerConstant; import software.amazon.awssdk.identity.spi.AwsSessionCredentialsIdentity; import software.amazon.awssdk.utils.Pair; /** * An interface which declares an algorithm that takes a request and a content-hash and signs the request according to the SigV4 * process. */ @SdkInternalApi public interface V4RequestSigner { /** * Retrieve an implementation of a V4RequestSigner, which signs the request, but does not add authentication to the request. */ static V4RequestSigner create(V4Properties properties, String contentHash) { return new DefaultV4RequestSigner(properties, contentHash); } /** * Retrieve an implementation of a V4RequestSigner, which signs the request and adds authentication through headers. */ static V4RequestSigner header(V4Properties properties) { return requestBuilder -> { // Add pre-requisites if (properties.getCredentials() instanceof AwsSessionCredentialsIdentity) { requestBuilder.putHeader(SignerConstant.X_AMZ_SECURITY_TOKEN, ((AwsSessionCredentialsIdentity) properties.getCredentials()).sessionToken()); } addHostHeader(requestBuilder); addDateHeader(requestBuilder, formatDateTime(properties.getCredentialScope().getInstant())); V4RequestSigningResult result = create(properties, getContentHash(requestBuilder)).sign(requestBuilder); // Add the signature within an authorization header String authHeader = AWS4_SIGNING_ALGORITHM + " Credential=" + properties.getCredentialScope().scope(properties.getCredentials()) + ", SignedHeaders=" + result.getCanonicalRequest().getSignedHeadersString() + ", Signature=" + result.getSignature(); requestBuilder.putHeader(SignerConstant.AUTHORIZATION, authHeader); return result; }; } /** * Retrieve an implementation of a V4RequestSigner, which signs the request and adds authentication through query parameters. */ static V4RequestSigner query(V4Properties properties) { return requestBuilder -> { // Add pre-requisites if (properties.getCredentials() instanceof AwsSessionCredentialsIdentity) { requestBuilder.putRawQueryParameter(SignerConstant.X_AMZ_SECURITY_TOKEN, ((AwsSessionCredentialsIdentity) properties.getCredentials()).sessionToken()); } // We have to add the host-header here explicitly, since query-signed request requires it in the signed-header param addHostHeader(requestBuilder); List<Pair<String, List<String>>> canonicalHeaders = getCanonicalHeaders(requestBuilder.build()); requestBuilder.putRawQueryParameter(SignerConstant.X_AMZ_ALGORITHM, AWS4_SIGNING_ALGORITHM); requestBuilder.putRawQueryParameter(SignerConstant.X_AMZ_DATE, properties.getCredentialScope().getDatetime()); requestBuilder.putRawQueryParameter(SignerConstant.X_AMZ_SIGNED_HEADERS, getSignedHeadersString(canonicalHeaders)); requestBuilder.putRawQueryParameter(SignerConstant.X_AMZ_CREDENTIAL, properties.getCredentialScope().scope(properties.getCredentials())); V4RequestSigningResult result = create(properties, getContentHash(requestBuilder)).sign(requestBuilder); // Add the signature requestBuilder.putRawQueryParameter(SignerConstant.X_AMZ_SIGNATURE, result.getSignature()); return result; }; } /** * Retrieve an implementation of a V4RequestSigner, which signs the request and adds authentication through query parameters, * which includes an expiration param, signalling how long a request signature is valid. */ static V4RequestSigner presigned(V4Properties properties, Duration expirationDuration) { return requestBuilder -> { // Add pre-requisites if (properties.getCredentials() instanceof AwsSessionCredentialsIdentity) { requestBuilder.putRawQueryParameter(SignerConstant.X_AMZ_SECURITY_TOKEN, ((AwsSessionCredentialsIdentity) properties.getCredentials()).sessionToken()); } // We have to add the host-header here explicitly, since pre-signed request requires it in the signed-header param addHostHeader(requestBuilder); // Pre-signed requests shouldn't have the content-hash header String contentHash = getContentHash(requestBuilder); requestBuilder.removeHeader(X_AMZ_CONTENT_SHA256); List<Pair<String, List<String>>> canonicalHeaders = getCanonicalHeaders(requestBuilder.build()); requestBuilder.putRawQueryParameter(SignerConstant.X_AMZ_ALGORITHM, AWS4_SIGNING_ALGORITHM); requestBuilder.putRawQueryParameter(SignerConstant.X_AMZ_DATE, properties.getCredentialScope().getDatetime()); requestBuilder.putRawQueryParameter(SignerConstant.X_AMZ_SIGNED_HEADERS, getSignedHeadersString(canonicalHeaders)); requestBuilder.putRawQueryParameter(SignerConstant.X_AMZ_CREDENTIAL, properties.getCredentialScope().scope(properties.getCredentials())); requestBuilder.putRawQueryParameter(SignerConstant.X_AMZ_EXPIRES, Long.toString(expirationDuration.getSeconds())); V4RequestSigningResult result = create(properties, contentHash).sign(requestBuilder); // Add the signature requestBuilder.putRawQueryParameter(SignerConstant.X_AMZ_SIGNATURE, result.getSignature()); return result; }; } /** * Retrieve an implementation of a V4RequestSigner to handle the anonymous credentials case, where the request is not * sigend at all. */ static V4RequestSigner anonymous(V4Properties properties) { return requestBuilder -> new V4RequestSigningResult("", new byte[] {}, null, null, requestBuilder); } /** * Given a request builder, sign the request and return a result containing the signed request and its properties. */ V4RequestSigningResult sign(SdkHttpRequest.Builder requestBuilder); }
2,580
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal/signer/V4RequestSigningResult.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.signer; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.SdkHttpRequest; /** * A container for data produced during and as a result of the SigV4 request signing process. */ @SdkInternalApi // TODO(sra-identity-auth): This is currently not @Immutable because signedRequest is a Builder. Is Builder needed? If it could // hold reference to SdkHttpRequest instead, this class would be @Immutable. public final class V4RequestSigningResult { private final String contentHash; private final byte[] signingKey; private final String signature; private final V4CanonicalRequest canonicalRequest; private final SdkHttpRequest.Builder signedRequest; public V4RequestSigningResult(String contentHash, byte[] signingKey, String signature, V4CanonicalRequest canonicalRequest, SdkHttpRequest.Builder signedRequest) { this.contentHash = contentHash; this.signingKey = signingKey.clone(); this.signature = signature; this.canonicalRequest = canonicalRequest; this.signedRequest = signedRequest; } public String getContentHash() { return contentHash; } public byte[] getSigningKey() { return signingKey.clone(); } public String getSignature() { return signature; } public V4CanonicalRequest getCanonicalRequest() { return canonicalRequest; } public SdkHttpRequest.Builder getSignedRequest() { return signedRequest; } }
2,581
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal/signer/FlexibleChecksummer.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.signer; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.ChecksumUtil.fromChecksumAlgorithm; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.ChecksumUtil.readAll; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerUtils.getBinaryRequestPayloadStream; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Collection; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import java.util.stream.Collectors; import org.reactivestreams.Publisher; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.checksums.spi.ChecksumAlgorithm; import software.amazon.awssdk.http.ContentStreamProvider; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.auth.aws.internal.signer.checksums.SdkChecksum; import software.amazon.awssdk.http.auth.aws.internal.signer.io.ChecksumInputStream; import software.amazon.awssdk.http.auth.aws.internal.signer.io.ChecksumSubscriber; import software.amazon.awssdk.utils.Validate; /** * A "flexible" implementation of a checksummer. It takes a map of checksums and their header names, computes them efficiently by * updating each checksum while reading the payload (once), and adds the computed checksum strings to the request using the given * header names in the map. This should be used in cases where a (flexible) checksum algorithm is present during signing. */ @SdkInternalApi public final class FlexibleChecksummer implements Checksummer { private final Collection<Option> options; private final Map<Option, SdkChecksum> optionToSdkChecksum; public FlexibleChecksummer(Option... options) { this.options = Arrays.asList(options); this.optionToSdkChecksum = this.options.stream().collect( Collectors.toMap(Function.identity(), o -> fromChecksumAlgorithm(o.algorithm)) ); } @Override public void checksum(ContentStreamProvider payload, SdkHttpRequest.Builder request) { InputStream payloadStream = getBinaryRequestPayloadStream(payload); ChecksumInputStream computingStream = new ChecksumInputStream( payloadStream, optionToSdkChecksum.values() ); readAll(computingStream); addChecksums(request); } @Override public CompletableFuture<Publisher<ByteBuffer>> checksum(Publisher<ByteBuffer> payload, SdkHttpRequest.Builder request) { ChecksumSubscriber checksumSubscriber = new ChecksumSubscriber(optionToSdkChecksum.values()); if (payload == null) { addChecksums(request); return CompletableFuture.completedFuture(null); } payload.subscribe(checksumSubscriber); CompletableFuture<Publisher<ByteBuffer>> result = checksumSubscriber.completeFuture(); result.thenRun(() -> addChecksums(request)); return result; } private void addChecksums(SdkHttpRequest.Builder request) { optionToSdkChecksum.forEach( (option, sdkChecksum) -> request.putHeader( option.headerName, option.formatter.apply(sdkChecksum.getChecksumBytes())) ); } public static Option.Builder option() { return Option.builder(); } public static class Option { private final ChecksumAlgorithm algorithm; private final String headerName; private final Function<byte[], String> formatter; Option(Builder builder) { this.algorithm = Validate.paramNotNull(builder.algorithm, "algorithm"); this.headerName = Validate.paramNotNull(builder.headerName, "headerName"); this.formatter = Validate.paramNotNull(builder.formatter, "formatter"); } public static Builder builder() { return new Builder(); } public static class Builder { private ChecksumAlgorithm algorithm; private String headerName; private Function<byte[], String> formatter; public Builder algorithm(ChecksumAlgorithm algorithm) { this.algorithm = algorithm; return this; } public Builder headerName(String headerName) { this.headerName = headerName; return this; } public Builder formatter(Function<byte[], String> formatter) { this.formatter = formatter; return this; } public Option build() { return new Option(this); } } } }
2,582
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal/signer/Checksummer.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.signer; import static software.amazon.awssdk.checksums.DefaultChecksumAlgorithm.SHA256; import static software.amazon.awssdk.http.auth.aws.internal.signer.FlexibleChecksummer.option; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.ChecksumUtil.ConstantChecksumAlgorithm; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.ChecksumUtil.checksumHeaderName; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerConstant.X_AMZ_CONTENT_SHA256; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.concurrent.CompletableFuture; import org.reactivestreams.Publisher; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.checksums.spi.ChecksumAlgorithm; import software.amazon.awssdk.http.ContentStreamProvider; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.utils.BinaryUtils; /** * An interface for defining how a checksum is formed from a payload synchronously and asynchronously. * <p> * The implementation may choose to also manipulate the request with the checksum, such as adding it as a header. */ @SdkInternalApi public interface Checksummer { /** * Get a default implementation of a checksummer, which calculates the SHA-256 checksum and places it in the * x-amz-content-sha256 header. */ static Checksummer create() { return new FlexibleChecksummer( option().headerName(X_AMZ_CONTENT_SHA256).algorithm(SHA256).formatter(BinaryUtils::toHex).build() ); } /** * Get a flexible checksummer that performs two checksums: the given checksum-algorithm and the SHA-256 checksum. It places * the SHA-256 checksum in x-amz-content-sha256 header, and the given checksum-algorithm in the x-amz-checksum-[name] header. */ static Checksummer forFlexibleChecksum(ChecksumAlgorithm checksumAlgorithm) { if (checksumAlgorithm != null) { return new FlexibleChecksummer( option().headerName(X_AMZ_CONTENT_SHA256).algorithm(SHA256).formatter(BinaryUtils::toHex) .build(), option().headerName(checksumHeaderName(checksumAlgorithm)).algorithm(checksumAlgorithm) .formatter(BinaryUtils::toBase64).build() ); } throw new IllegalArgumentException("Checksum Algorithm cannot be null!"); } /** * Get a precomputed checksummer which places the precomputed checksum to the x-amz-content-sha256 header. */ static Checksummer forPrecomputed256Checksum(String precomputedSha256) { return new PrecomputedSha256Checksummer(() -> precomputedSha256); } /** * Get a flexible checksummer that performs two checksums: the given checksum-algorithm and a precomputed checksum from the * given checksum string. It places the precomputed checksum in x-amz-content-sha256 header, and the given checksum-algorithm * in the x-amz-checksum-[name] header. */ static Checksummer forFlexibleChecksum(String precomputedSha256, ChecksumAlgorithm checksumAlgorithm) { if (checksumAlgorithm != null) { return new FlexibleChecksummer( option().headerName(X_AMZ_CONTENT_SHA256).algorithm(new ConstantChecksumAlgorithm(precomputedSha256)) .formatter(b -> new String(b, StandardCharsets.UTF_8)).build(), option().headerName(checksumHeaderName(checksumAlgorithm)).algorithm(checksumAlgorithm) .formatter(BinaryUtils::toBase64).build() ); } throw new IllegalArgumentException("Checksum Algorithm cannot be null!"); } static Checksummer forNoOp() { return new FlexibleChecksummer(); } /** * Given a payload, calculate a checksum and add it to the request. */ void checksum(ContentStreamProvider payload, SdkHttpRequest.Builder request); /** * Given a payload, asynchronously calculate a checksum and promise to add it to the request. */ CompletableFuture<Publisher<ByteBuffer>> checksum(Publisher<ByteBuffer> payload, SdkHttpRequest.Builder request); }
2,583
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal/signer/RollingSigner.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.signer; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerUtils.computeSignature; import static software.amazon.awssdk.utils.BinaryUtils.toHex; import java.util.function.Function; import software.amazon.awssdk.annotations.SdkInternalApi; /** * A class which calculates a rolling signature of arbitrary data using HMAC-SHA256. Each time a signature is calculated, the * prior calculation is incorporated, hence "rolling". */ @SdkInternalApi public final class RollingSigner { private final byte[] signingKey; private final String seedSignature; private String previousSignature; public RollingSigner(byte[] signingKey, String seedSignature) { this.seedSignature = seedSignature; this.previousSignature = seedSignature; this.signingKey = signingKey.clone(); } /** * Using a template that incorporates the previous calculated signature, sign the string and return it. */ public String sign(Function<String, String> stringToSignTemplate) { String stringToSign = stringToSignTemplate.apply(previousSignature); byte[] bytes = computeSignature(stringToSign, signingKey); previousSignature = toHex(bytes); return previousSignature; } public void reset() { previousSignature = seedSignature; } }
2,584
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal/signer/DefaultV4RequestSigner.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.signer; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerConstant.AWS4_SIGNING_ALGORITHM; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerUtils.deriveSigningKey; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerUtils.hashCanonicalRequest; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerConstant; import software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerUtils; import software.amazon.awssdk.utils.BinaryUtils; import software.amazon.awssdk.utils.Logger; /** * The default implementation of a v4-request-signer. It performs each step of the SigV4 signing process, but does not add the * signature or auth information to the request itself. * <p> * All signing information, such as signature, signing key, canonical request, etc. is present in result object that is returned. * This can be used by the caller to add the auth info to the request, such as adding the signature as a query parameter or * building an authorization header using the signature and canonical request headers. */ @SdkInternalApi public final class DefaultV4RequestSigner implements V4RequestSigner { private static final Logger LOG = Logger.loggerFor(DefaultV4RequestSigner.class); private final V4Properties properties; private final String contentHash; public DefaultV4RequestSigner(V4Properties properties, String contentHash) { this.properties = properties; this.contentHash = contentHash; } @Override public V4RequestSigningResult sign(SdkHttpRequest.Builder requestBuilder) { // Step 1: Create a canonical request V4CanonicalRequest canonicalRequest = createCanonicalRequest(requestBuilder.build(), contentHash); // Step 2: Create a hash of the canonical request String canonicalRequestHash = hashCanonicalRequest(canonicalRequest.getCanonicalRequestString()); // Step 2: Create a hash of the canonical request String stringToSign = createSignString(canonicalRequestHash); // Step 4: Calculate the signature byte[] signingKey = createSigningKey(); String signature = createSignature(stringToSign, signingKey); // Step 5: Return the results (including signature) of request signing return new V4RequestSigningResult(contentHash, signingKey, signature, canonicalRequest, requestBuilder); } private V4CanonicalRequest createCanonicalRequest(SdkHttpRequest request, String contentHash) { return new V4CanonicalRequest(request, contentHash, new V4CanonicalRequest.Options( properties.shouldDoubleUrlEncode(), properties.shouldNormalizePath() )); } private String createSignString(String canonicalRequestHash) { LOG.debug(() -> "AWS4 Canonical Request Hash: " + canonicalRequestHash); String stringToSign = AWS4_SIGNING_ALGORITHM + SignerConstant.LINE_SEPARATOR + properties.getCredentialScope().getDatetime() + SignerConstant.LINE_SEPARATOR + properties.getCredentialScope().scope() + SignerConstant.LINE_SEPARATOR + canonicalRequestHash; LOG.debug(() -> "AWS4 String to sign: " + stringToSign); return stringToSign; } private byte[] createSigningKey() { return deriveSigningKey(properties.getCredentials(), properties.getCredentialScope()); } private String createSignature(String stringToSign, byte[] signingKey) { return BinaryUtils.toHex(SignerUtils.computeSignature(stringToSign, signingKey)); } }
2,585
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal/signer/DefaultAwsV4HttpSigner.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.signer; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.ChecksumUtil.checksumHeaderName; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.CredentialUtils.sanitizeCredentials; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.OptionalDependencyLoaderUtil.getEventStreamV4PayloadSigner; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerConstant.PRESIGN_URL_MAX_EXPIRATION_DURATION; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerConstant.STREAMING_EVENTS_PAYLOAD; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerConstant.STREAMING_SIGNED_PAYLOAD; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerConstant.STREAMING_SIGNED_PAYLOAD_TRAILER; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerConstant.STREAMING_UNSIGNED_PAYLOAD_TRAILER; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerConstant.UNSIGNED_PAYLOAD; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerConstant.X_AMZ_TRAILER; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.checksums.spi.ChecksumAlgorithm; import software.amazon.awssdk.http.ContentStreamProvider; import software.amazon.awssdk.http.Header; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.auth.aws.internal.signer.util.CredentialUtils; import software.amazon.awssdk.http.auth.aws.signer.AwsV4HttpSigner; 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.AwsCredentialsIdentity; /** * An implementation of a {@link AwsV4HttpSigner} that uses properties to compose v4-signers in order to delegate signing of a * request and payload (if applicable) accordingly. */ @SdkInternalApi public final class DefaultAwsV4HttpSigner implements AwsV4HttpSigner { private static final int DEFAULT_CHUNK_SIZE_IN_BYTES = 128 * 1024; @Override public SignedRequest sign(SignRequest<? extends AwsCredentialsIdentity> request) { Checksummer checksummer = checksummer(request, null); V4Properties v4Properties = v4Properties(request); V4RequestSigner v4RequestSigner = v4RequestSigner(request, v4Properties); V4PayloadSigner payloadSigner = v4PayloadSigner(request, v4Properties); return doSign(request, checksummer, v4RequestSigner, payloadSigner); } @Override public CompletableFuture<AsyncSignedRequest> signAsync(AsyncSignRequest<? extends AwsCredentialsIdentity> request) { Checksummer checksummer = asyncChecksummer(request); V4Properties v4Properties = v4Properties(request); V4RequestSigner v4RequestSigner = v4RequestSigner(request, v4Properties); V4PayloadSigner payloadSigner = v4PayloadAsyncSigner(request, v4Properties); return doSign(request, checksummer, v4RequestSigner, payloadSigner); } private static V4Properties v4Properties(BaseSignRequest<?, ? extends AwsCredentialsIdentity> request) { Clock signingClock = request.requireProperty(SIGNING_CLOCK, Clock.systemUTC()); Instant signingInstant = signingClock.instant(); AwsCredentialsIdentity credentials = sanitizeCredentials(request.identity()); String regionName = request.requireProperty(AwsV4HttpSigner.REGION_NAME); String serviceSigningName = request.requireProperty(SERVICE_SIGNING_NAME); CredentialScope credentialScope = new CredentialScope(regionName, serviceSigningName, signingInstant); boolean doubleUrlEncode = request.requireProperty(DOUBLE_URL_ENCODE, true); boolean normalizePath = request.requireProperty(NORMALIZE_PATH, true); return V4Properties.builder() .credentials(credentials) .credentialScope(credentialScope) .signingClock(signingClock) .doubleUrlEncode(doubleUrlEncode) .normalizePath(normalizePath) .build(); } private static V4RequestSigner v4RequestSigner( BaseSignRequest<?, ? extends AwsCredentialsIdentity> request, V4Properties v4Properties) { AuthLocation authLocation = request.requireProperty(AUTH_LOCATION, AuthLocation.HEADER); Duration expirationDuration = request.property(EXPIRATION_DURATION); boolean isAnonymous = CredentialUtils.isAnonymous(request.identity()); if (isAnonymous) { return V4RequestSigner.anonymous(v4Properties); } Function<V4Properties, V4RequestSigner> requestSigner; switch (authLocation) { case HEADER: if (expirationDuration != null) { throw new UnsupportedOperationException( String.format("%s is not supported for %s.", EXPIRATION_DURATION, AuthLocation.HEADER)); } requestSigner = V4RequestSigner::header; break; case QUERY_STRING: requestSigner = expirationDuration == null ? V4RequestSigner::query : properties -> V4RequestSigner.presigned(properties, validateExpirationDuration(expirationDuration)); break; default: throw new UnsupportedOperationException("Unsupported authLocation " + authLocation); } return requestSigner.apply(v4Properties); } private static Checksummer checksummer(BaseSignRequest<?, ? extends AwsCredentialsIdentity> request, Boolean isPayloadSigningOverride) { boolean isPayloadSigning = isPayloadSigningOverride != null ? isPayloadSigningOverride : isPayloadSigning(request); boolean isEventStreaming = isEventStreaming(request.request()); boolean hasChecksumHeader = hasChecksumHeader(request); boolean isChunkEncoding = request.requireProperty(CHUNK_ENCODING_ENABLED, false); boolean isTrailing = request.request().firstMatchingHeader(X_AMZ_TRAILER).isPresent(); boolean isFlexible = request.hasProperty(CHECKSUM_ALGORITHM) && !hasChecksumHeader; boolean isAnonymous = CredentialUtils.isAnonymous(request.identity()); if (isEventStreaming) { return Checksummer.forPrecomputed256Checksum(STREAMING_EVENTS_PAYLOAD); } if (isPayloadSigning) { if (isChunkEncoding) { if (isFlexible || isTrailing) { return Checksummer.forPrecomputed256Checksum(STREAMING_SIGNED_PAYLOAD_TRAILER); } return Checksummer.forPrecomputed256Checksum(STREAMING_SIGNED_PAYLOAD); } if (isFlexible) { return Checksummer.forFlexibleChecksum(request.property(CHECKSUM_ALGORITHM)); } return Checksummer.create(); } if (isFlexible || isTrailing) { if (isChunkEncoding) { return Checksummer.forPrecomputed256Checksum(STREAMING_UNSIGNED_PAYLOAD_TRAILER); } } if (isFlexible) { return Checksummer.forFlexibleChecksum(UNSIGNED_PAYLOAD, request.property(CHECKSUM_ALGORITHM)); } if (isAnonymous) { return Checksummer.forNoOp(); } return Checksummer.forPrecomputed256Checksum(UNSIGNED_PAYLOAD); } /** * This is needed because of the pre-existing gap (pre-SRA) in behavior where we don't treat async + streaming + http + * unsigned-payload as signed-payload (fallback). We have to do some finagling of the payload-signing options before * calling the actual checksummer() method */ private static Checksummer asyncChecksummer(BaseSignRequest<?, ? extends AwsCredentialsIdentity> request) { boolean isHttp = !"https".equals(request.request().protocol()); boolean isPayloadSigning = isPayloadSigning(request); boolean isChunkEncoding = request.requireProperty(CHUNK_ENCODING_ENABLED, false); boolean shouldTreatAsUnsigned = isHttp && isPayloadSigning && isChunkEncoding; // set the override to false if it should be treated as unsigned, otherwise, null should be passed so that the normal // check for payload signing is done. Boolean overridePayloadSigning = shouldTreatAsUnsigned ? false : null; return checksummer(request, overridePayloadSigning); } private static V4PayloadSigner v4PayloadSigner( SignRequest<? extends AwsCredentialsIdentity> request, V4Properties properties) { boolean isPayloadSigning = isPayloadSigning(request); boolean isEventStreaming = isEventStreaming(request.request()); boolean isChunkEncoding = request.requireProperty(CHUNK_ENCODING_ENABLED, false); boolean isTrailing = request.request().firstMatchingHeader(X_AMZ_TRAILER).isPresent(); boolean isFlexible = request.hasProperty(CHECKSUM_ALGORITHM) && !hasChecksumHeader(request); if (isEventStreaming) { if (isPayloadSigning) { return getEventStreamV4PayloadSigner( properties.getCredentials(), properties.getCredentialScope(), properties.getSigningClock() ); } throw new UnsupportedOperationException("Unsigned payload is not supported with event-streaming."); } if (useChunkEncoding(isPayloadSigning, isChunkEncoding, isTrailing || isFlexible)) { return AwsChunkedV4PayloadSigner.builder() .credentialScope(properties.getCredentialScope()) .chunkSize(DEFAULT_CHUNK_SIZE_IN_BYTES) .checksumAlgorithm(request.property(CHECKSUM_ALGORITHM)) .build(); } return V4PayloadSigner.create(); } private static V4PayloadSigner v4PayloadAsyncSigner( AsyncSignRequest<? extends AwsCredentialsIdentity> request, V4Properties properties) { boolean isPayloadSigning = request.requireProperty(PAYLOAD_SIGNING_ENABLED, true); boolean isEventStreaming = isEventStreaming(request.request()); boolean isChunkEncoding = request.requireProperty(CHUNK_ENCODING_ENABLED, false); if (isEventStreaming) { if (isPayloadSigning) { return getEventStreamV4PayloadSigner( properties.getCredentials(), properties.getCredentialScope(), properties.getSigningClock() ); } throw new UnsupportedOperationException("Unsigned payload is not supported with event-streaming."); } if (isChunkEncoding && isPayloadSigning) { // TODO(sra-identity-and-auth): We need to implement aws-chunk content-encoding for async. // For now, we basically have to treat this as an unsigned case because there are existing s3 use-cases for // Unsigned-payload + HTTP. These requests SHOULD be signed-payload, but are not pre-SRA, hence the problem. This // will be taken care of in HttpChecksumStage for now, so we shouldn't throw an unsupported exception here, we // should just fall through to the default since it will already encoded by the time it gets here. return V4PayloadSigner.create(); } return V4PayloadSigner.create(); } private static SignedRequest doSign(SignRequest<? extends AwsCredentialsIdentity> request, Checksummer checksummer, V4RequestSigner requestSigner, V4PayloadSigner payloadSigner) { SdkHttpRequest.Builder requestBuilder = request.request().toBuilder(); ContentStreamProvider requestPayload = request.payload().orElse(null); checksummer.checksum(requestPayload, requestBuilder); payloadSigner.beforeSigning(requestBuilder, requestPayload); V4RequestSigningResult requestSigningResult = requestSigner.sign(requestBuilder); ContentStreamProvider signedPayload = null; if (requestPayload != null) { signedPayload = payloadSigner.sign(requestPayload, requestSigningResult); } return SignedRequest.builder() .request(requestSigningResult.getSignedRequest().build()) .payload(signedPayload) .build(); } private static CompletableFuture<AsyncSignedRequest> doSign(AsyncSignRequest<? extends AwsCredentialsIdentity> request, Checksummer checksummer, V4RequestSigner requestSigner, V4PayloadSigner payloadSigner) { SdkHttpRequest.Builder requestBuilder = request.request().toBuilder(); return checksummer.checksum(request.payload().orElse(null), requestBuilder) .thenApply(payload -> { V4RequestSigningResult requestSigningResultFuture = requestSigner.sign(requestBuilder); return AsyncSignedRequest.builder() .request(requestSigningResultFuture.getSignedRequest().build()) .payload(payloadSigner.signAsync(payload, requestSigningResultFuture)) .build(); }); } private static Duration validateExpirationDuration(Duration expirationDuration) { if (!isBetweenInclusive(Duration.ofSeconds(1), expirationDuration, PRESIGN_URL_MAX_EXPIRATION_DURATION)) { throw new IllegalArgumentException( "Requests that are pre-signed by SigV4 algorithm are valid for at least 1 second and at most 7" + " days. The expiration duration set on the current request [" + expirationDuration + "]" + " does not meet these bounds." ); } return expirationDuration; } private static boolean isBetweenInclusive(Duration start, Duration x, Duration end) { return start.compareTo(x) <= 0 && x.compareTo(end) <= 0; } private static boolean isPayloadSigning(BaseSignRequest<?, ? extends AwsCredentialsIdentity> request) { boolean isAnonymous = CredentialUtils.isAnonymous(request.identity()); boolean isPayloadSigningEnabled = request.requireProperty(PAYLOAD_SIGNING_ENABLED, true); boolean isEncrypted = "https".equals(request.request().protocol()); return !isAnonymous && (isPayloadSigningEnabled || !isEncrypted); } private static boolean isEventStreaming(SdkHttpRequest request) { return "application/vnd.amazon.eventstream".equals(request.firstMatchingHeader(Header.CONTENT_TYPE).orElse("")); } private static boolean hasChecksumHeader(BaseSignRequest<?, ? extends AwsCredentialsIdentity> request) { ChecksumAlgorithm checksumAlgorithm = request.property(CHECKSUM_ALGORITHM); if (checksumAlgorithm != null) { String checksumHeaderName = checksumHeaderName(checksumAlgorithm); return request.request().firstMatchingHeader(checksumHeaderName).isPresent(); } return false; } private static boolean useChunkEncoding(boolean payloadSigningEnabled, boolean chunkEncodingEnabled, boolean isTrailingOrFlexible) { return (payloadSigningEnabled && chunkEncodingEnabled) || (chunkEncodingEnabled && isTrailingOrFlexible); } }
2,586
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal/signer/CredentialScope.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.signer; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerConstant.AWS4_TERMINATOR; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerUtils.formatDate; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerUtils.formatDateTime; import java.time.Instant; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; @SdkInternalApi @Immutable public final class CredentialScope { private final String region; private final String service; private final Instant instant; public CredentialScope(String region, String service, Instant instant) { this.region = region; this.service = service; this.instant = instant; } public String getRegion() { return region; } public String getService() { return service; } public Instant getInstant() { return instant; } public String getDate() { return formatDate(instant); } public String getDatetime() { return formatDateTime(instant); } public String scope() { return getDate() + "/" + region + "/" + service + "/" + AWS4_TERMINATOR; } public String scope(AwsCredentialsIdentity credentials) { return credentials.accessKeyId() + "/" + scope(); } }
2,587
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal/signer/V4PayloadSigner.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.signer; import java.nio.ByteBuffer; import org.reactivestreams.Publisher; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.ContentStreamProvider; import software.amazon.awssdk.http.SdkHttpRequest; /** * An interface for defining how to sign a payload via SigV4. */ @SdkInternalApi public interface V4PayloadSigner { /** * Get a default implementation of a SigV4 payload signer. */ static V4PayloadSigner create() { return new DefaultV4PayloadSigner(); } /** * Given a payload and result of request signing, sign the payload via the SigV4 process. */ ContentStreamProvider sign(ContentStreamProvider payload, V4RequestSigningResult requestSigningResult); /** * Given a payload and result of request signing, sign the payload via the SigV4 process. */ Publisher<ByteBuffer> signAsync(Publisher<ByteBuffer> payload, V4RequestSigningResult requestSigningResult); /** * Modify a request before it is signed, such as changing headers or query-parameters. */ default void beforeSigning(SdkHttpRequest.Builder request, ContentStreamProvider payload) { } }
2,588
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal/signer/V4CanonicalRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.signer; import static software.amazon.awssdk.utils.StringUtils.lowerCase; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerConstant; import software.amazon.awssdk.utils.Pair; import software.amazon.awssdk.utils.StringUtils; import software.amazon.awssdk.utils.http.SdkHttpUtils; /** * A class that represents a canonical request in AWS, as documented: * <p> * https://docs.aws.amazon.com/IAM/latest/UserGuide/create-signed-request.html#create-canonical-request * </p> */ @SdkInternalApi @Immutable public final class V4CanonicalRequest { private static final List<String> HEADERS_TO_IGNORE_IN_LOWER_CASE = Arrays.asList("connection", "x-amzn-trace-id", "user-agent", "expect"); private final SdkHttpRequest request; private final String contentHash; private final Options options; // Compute these fields lazily when, and, if needed. private String canonicalUri; private SortedMap<String, List<String>> canonicalParams; private List<Pair<String, List<String>>> canonicalHeaders; private String canonicalQueryString; private String canonicalHeadersString; private String signedHeadersString; private String canonicalRequestString; /** * Create a canonical request. * <p> * Each parameter of a canonical request is set upon creation of this object. * <p> * To get such a parameter (i.e. the canonical request string), simply call the getter for that parameter (i.e. * getCanonicalRequestString()) */ public V4CanonicalRequest(SdkHttpRequest request, String contentHash, Options options) { this.request = request; this.contentHash = contentHash; this.options = options; } /** * Get the string representing which headers are part of the signing process. Header names are separated by a semicolon. */ public String getSignedHeadersString() { if (signedHeadersString == null) { signedHeadersString = getSignedHeadersString(canonicalHeaders()); } return signedHeadersString; } /** * Get the canonical request string. */ public String getCanonicalRequestString() { if (canonicalRequestString == null) { canonicalRequestString = getCanonicalRequestString(request.method().toString(), canonicalUri(), canonicalQueryString(), canonicalHeadersString(), getSignedHeadersString(), contentHash); } return canonicalRequestString; } private SortedMap<String, List<String>> canonicalQueryParams() { if (canonicalParams == null) { canonicalParams = getCanonicalQueryParams(request); } return canonicalParams; } private List<Pair<String, List<String>>> canonicalHeaders() { if (canonicalHeaders == null) { canonicalHeaders = getCanonicalHeaders(request); } return canonicalHeaders; } private String canonicalUri() { if (canonicalUri == null) { canonicalUri = getCanonicalUri(request, options); } return canonicalUri; } private String canonicalQueryString() { if (canonicalQueryString == null) { canonicalQueryString = getCanonicalQueryString(canonicalQueryParams()); } return canonicalQueryString; } private String canonicalHeadersString() { if (canonicalHeadersString == null) { canonicalHeadersString = getCanonicalHeadersString(canonicalHeaders()); } return canonicalHeadersString; } /** * Get the list of headers that are to be signed. * <p> * If calling from a site with the request object handy, this method should be used instead of passing the headers themselves, * as doing so creates a redundant copy. */ public static List<Pair<String, List<String>>> getCanonicalHeaders(SdkHttpRequest request) { List<Pair<String, List<String>>> result = new ArrayList<>(request.numHeaders()); // headers retrieved from the request are already sorted case-insensitively request.forEachHeader((key, value) -> { String lowerCaseHeader = lowerCase(key); if (!HEADERS_TO_IGNORE_IN_LOWER_CASE.contains(lowerCaseHeader)) { result.add(Pair.of(lowerCaseHeader, value)); } }); result.sort(Comparator.comparing(Pair::left)); return result; } /** * Get the list of headers that are to be signed. The supplied map of headers is expected to be sorted case-insensitively. */ public static List<Pair<String, List<String>>> getCanonicalHeaders(Map<String, List<String>> headers) { List<Pair<String, List<String>>> result = new ArrayList<>(headers.size()); headers.forEach((key, value) -> { String lowerCaseHeader = lowerCase(key); if (!HEADERS_TO_IGNORE_IN_LOWER_CASE.contains(lowerCaseHeader)) { result.add(Pair.of(lowerCaseHeader, value)); } }); result.sort(Comparator.comparing(Pair::left)); return result; } /** * Get the string representing the headers that will be signed and their values. The input list is expected to be sorted * case-insensitively. * <p> * The output string will have header names as lower-case, sorted in alphabetical order, and followed by a colon. * <p> * Values are trimmed of any leading/trailing spaces, sequential spaces are converted to single space, and multiple values are * comma separated. * <p> * Each header-value pair is separated by a newline. */ public static String getCanonicalHeadersString(List<Pair<String, List<String>>> canonicalHeaders) { StringBuilder result = new StringBuilder(512); canonicalHeaders.forEach(header -> { result.append(header.left()); result.append(":"); for (String headerValue : header.right()) { addAndTrim(result, headerValue); result.append(","); } result.setLength(result.length() - 1); result.append("\n"); }); return result.toString(); } /** * Get the string representing which headers are part of the signing process. Header names are separated by a semicolon. */ public static String getSignedHeadersString(List<Pair<String, List<String>>> canonicalHeaders) { String signedHeadersString; StringBuilder headersString = new StringBuilder(512); for (Pair<String, List<String>> header : canonicalHeaders) { headersString.append(header.left()).append(";"); } // get rid of trailing semicolon signedHeadersString = headersString.toString(); boolean trimTrailingSemicolon = signedHeadersString.length() > 1 && signedHeadersString.endsWith(";"); if (trimTrailingSemicolon) { signedHeadersString = signedHeadersString.substring(0, signedHeadersString.length() - 1); } return signedHeadersString; } /** * Get the canonical request string. * <p> * Each {@link String} parameter is separated by a newline character. */ private static String getCanonicalRequestString(String httpMethod, String canonicalUri, String canonicalParamsString, String canonicalHeadersString, String signedHeadersString, String contentHash) { return httpMethod + SignerConstant.LINE_SEPARATOR + canonicalUri + SignerConstant.LINE_SEPARATOR + canonicalParamsString + SignerConstant.LINE_SEPARATOR + canonicalHeadersString + SignerConstant.LINE_SEPARATOR + signedHeadersString + SignerConstant.LINE_SEPARATOR + contentHash; } /** * "The addAndTrim function removes excess white space before and after values, and converts sequential spaces to a single * space." * <p> * https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html * <p> * The collapse-whitespace logic is equivalent to: * <pre> * value.replaceAll("\\s+", " ") * </pre> * but does not create a Pattern object that needs to compile the match string; it also prevents us from having to make a * Matcher object as well. */ private static void addAndTrim(StringBuilder result, String value) { int lengthBefore = result.length(); boolean isStart = true; boolean previousIsWhiteSpace = false; for (int i = 0; i < value.length(); i++) { char ch = value.charAt(i); if (isWhiteSpace(ch)) { if (previousIsWhiteSpace || isStart) { continue; } result.append(' '); previousIsWhiteSpace = true; } else { result.append(ch); isStart = false; previousIsWhiteSpace = false; } } if (lengthBefore == result.length()) { return; } int lastNonWhitespaceChar = result.length() - 1; while (isWhiteSpace(result.charAt(lastNonWhitespaceChar))) { --lastNonWhitespaceChar; } result.setLength(lastNonWhitespaceChar + 1); } /** * Get the uri-encoded version of the absolute path component URL. * <p> * If the path is empty, a single-forward slash ('/') is returned. */ private static String getCanonicalUri(SdkHttpRequest request, Options options) { String path = options.normalizePath ? request.getUri().normalize().getRawPath() : request.encodedPath(); if (StringUtils.isEmpty(path)) { return "/"; } if (options.doubleUrlEncode) { path = SdkHttpUtils.urlEncodeIgnoreSlashes(path); } if (!path.startsWith("/")) { path += "/"; } // Normalization can leave a trailing slash at the end of the resource path, // even if the input path doesn't end with one. Example input: /foo/bar/. // Remove the trailing slash if the input path doesn't end with one. boolean trimTrailingSlash = options.normalizePath && path.length() > 1 && !request.getUri().getPath().endsWith("/") && path.charAt(path.length() - 1) == '/'; if (trimTrailingSlash) { path = path.substring(0, path.length() - 1); } return path; } /** * Get the sorted map of query parameters that are to be signed. */ private static SortedMap<String, List<String>> getCanonicalQueryParams(SdkHttpRequest request) { SortedMap<String, List<String>> sorted = new TreeMap<>(); // Signing protocol expects the param values also to be sorted after url // encoding in addition to sorted parameter names. request.forEachRawQueryParameter((key, values) -> { if (StringUtils.isEmpty(key)) { // Do not sign empty keys. return; } String encodedParamName = SdkHttpUtils.urlEncode(key); List<String> encodedValues = new ArrayList<>(values.size()); for (String value : values) { String encodedValue = SdkHttpUtils.urlEncode(value); // Null values should be treated as empty for the purposes of signing, not missing. // For example "?foo=" instead of "?foo". String signatureFormattedEncodedValue = encodedValue == null ? "" : encodedValue; encodedValues.add(signatureFormattedEncodedValue); } Collections.sort(encodedValues); sorted.put(encodedParamName, encodedValues); }); return sorted; } /** * Get the string representing query string parameters. Parameters are URL-encoded and separated by an ampersand. * <p> * Reserved characters are percent-encoded, names and values are encoded separately and empty parameters have an equals-sign * appended before encoding. * <p> * After encoding, parameters are sorted alphabetically by key name. * <p> * If no query string is given, an empty string ("") is returned. */ private static String getCanonicalQueryString(SortedMap<String, List<String>> canonicalParams) { if (canonicalParams.isEmpty()) { return ""; } StringBuilder stringBuilder = new StringBuilder(512); SdkHttpUtils.flattenQueryParameters(stringBuilder, canonicalParams); return stringBuilder.toString(); } private static boolean isWhiteSpace(char ch) { return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\u000b' || ch == '\r' || ch == '\f'; } /** * A class for representing options used when creating a {@link V4CanonicalRequest} */ public static class Options { final boolean doubleUrlEncode; final boolean normalizePath; public Options(boolean doubleUrlEncode, boolean normalizePath) { this.doubleUrlEncode = doubleUrlEncode; this.normalizePath = normalizePath; } } }
2,589
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal/signer/DefaultV4PayloadSigner.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.signer; import java.nio.ByteBuffer; import org.reactivestreams.Publisher; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.ContentStreamProvider; /** * A default implementation of a payload signer that is a no-op, since payloads are most commonly unsigned. */ @SdkInternalApi public class DefaultV4PayloadSigner implements V4PayloadSigner { @Override public ContentStreamProvider sign(ContentStreamProvider payload, V4RequestSigningResult requestSigningResult) { return payload; } @Override public Publisher<ByteBuffer> signAsync(Publisher<ByteBuffer> payload, V4RequestSigningResult requestSigningResult) { return payload; } }
2,590
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal/signer/V4Properties.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.signer; import java.time.Clock; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.auth.spi.signer.BaseSignRequest; import software.amazon.awssdk.http.auth.spi.signer.SignerProperty; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.utils.Validate; /** * A class which contains "properties" relevant to SigV4. These properties can be derived {@link SignerProperty}'s on a * {@link BaseSignRequest}. */ @SdkInternalApi @Immutable public final class V4Properties { private final AwsCredentialsIdentity credentials; private final CredentialScope credentialScope; private final Clock signingClock; private final boolean doubleUrlEncode; private final boolean normalizePath; private V4Properties(Builder builder) { this.credentials = Validate.paramNotNull(builder.credentials, "Credentials"); this.credentialScope = Validate.paramNotNull(builder.credentialScope, "CredentialScope"); this.signingClock = Validate.paramNotNull(builder.signingClock, "SigningClock"); this.doubleUrlEncode = Validate.getOrDefault(builder.doubleUrlEncode, () -> true); this.normalizePath = Validate.getOrDefault(builder.normalizePath, () -> true); } public static Builder builder() { return new Builder(); } public AwsCredentialsIdentity getCredentials() { return credentials; } public CredentialScope getCredentialScope() { return credentialScope; } public Clock getSigningClock() { return signingClock; } public boolean shouldDoubleUrlEncode() { return doubleUrlEncode; } public boolean shouldNormalizePath() { return normalizePath; } public static class Builder { private AwsCredentialsIdentity credentials; private CredentialScope credentialScope; private Clock signingClock; private Boolean doubleUrlEncode; private Boolean normalizePath; public Builder credentials(AwsCredentialsIdentity credentials) { this.credentials = Validate.paramNotNull(credentials, "Credentials"); return this; } public Builder credentialScope(CredentialScope credentialScope) { this.credentialScope = Validate.paramNotNull(credentialScope, "CredentialScope"); return this; } public Builder signingClock(Clock signingClock) { this.signingClock = signingClock; return this; } public Builder doubleUrlEncode(Boolean doubleUrlEncode) { this.doubleUrlEncode = doubleUrlEncode; return this; } public Builder normalizePath(Boolean normalizePath) { this.normalizePath = normalizePath; return this; } public V4Properties build() { return new V4Properties(this); } } }
2,591
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal/signer/AwsChunkedV4PayloadSigner.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.signer; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.ChecksumUtil.checksumHeaderName; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.ChecksumUtil.fromChecksumAlgorithm; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerConstant.AWS_CHUNKED; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerConstant.CONTENT_ENCODING; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerConstant.STREAMING_SIGNED_PAYLOAD; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerConstant.STREAMING_SIGNED_PAYLOAD_TRAILER; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerConstant.STREAMING_UNSIGNED_PAYLOAD_TRAILER; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerConstant.X_AMZ_CONTENT_SHA256; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerConstant.X_AMZ_TRAILER; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.SignerUtils.moveContentLength; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.reactivestreams.Publisher; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.checksums.spi.ChecksumAlgorithm; import software.amazon.awssdk.http.ContentStreamProvider; import software.amazon.awssdk.http.Header; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.auth.aws.internal.signer.checksums.SdkChecksum; import software.amazon.awssdk.http.auth.aws.internal.signer.chunkedencoding.ChecksumTrailerProvider; import software.amazon.awssdk.http.auth.aws.internal.signer.chunkedencoding.ChunkedEncodedInputStream; import software.amazon.awssdk.http.auth.aws.internal.signer.chunkedencoding.SigV4ChunkExtensionProvider; import software.amazon.awssdk.http.auth.aws.internal.signer.chunkedencoding.SigV4TrailerProvider; import software.amazon.awssdk.http.auth.aws.internal.signer.chunkedencoding.TrailerProvider; import software.amazon.awssdk.http.auth.aws.internal.signer.io.ChecksumInputStream; import software.amazon.awssdk.http.auth.aws.internal.signer.io.ResettableContentStreamProvider; import software.amazon.awssdk.utils.BinaryUtils; import software.amazon.awssdk.utils.Pair; import software.amazon.awssdk.utils.StringInputStream; import software.amazon.awssdk.utils.Validate; /** * An implementation of a V4PayloadSigner which chunk-encodes a payload, optionally adding a chunk-signature chunk-extension, * and/or trailers representing trailing headers with their signature at the end. */ @SdkInternalApi public final class AwsChunkedV4PayloadSigner implements V4PayloadSigner { private final CredentialScope credentialScope; private final int chunkSize; private final ChecksumAlgorithm checksumAlgorithm; private final List<Pair<String, List<String>>> preExistingTrailers = new ArrayList<>(); private AwsChunkedV4PayloadSigner(Builder builder) { this.credentialScope = Validate.paramNotNull(builder.credentialScope, "CredentialScope"); this.chunkSize = Validate.isPositive(builder.chunkSize, "ChunkSize"); this.checksumAlgorithm = builder.checksumAlgorithm; } public static Builder builder() { return new Builder(); } @Override public ContentStreamProvider sign(ContentStreamProvider payload, V4RequestSigningResult requestSigningResult) { SdkHttpRequest.Builder request = requestSigningResult.getSignedRequest(); String checksum = request.firstMatchingHeader(X_AMZ_CONTENT_SHA256).orElseThrow( () -> new IllegalArgumentException(X_AMZ_CONTENT_SHA256 + " must be set!") ); ChunkedEncodedInputStream.Builder chunkedEncodedInputStreamBuilder = ChunkedEncodedInputStream .builder() .inputStream(payload.newStream()) .chunkSize(chunkSize) .header(chunk -> Integer.toHexString(chunk.length).getBytes(StandardCharsets.UTF_8)); preExistingTrailers.forEach(trailer -> chunkedEncodedInputStreamBuilder.addTrailer(() -> trailer)); switch (checksum) { case STREAMING_SIGNED_PAYLOAD: { RollingSigner rollingSigner = new RollingSigner(requestSigningResult.getSigningKey(), requestSigningResult.getSignature()); chunkedEncodedInputStreamBuilder.addExtension(new SigV4ChunkExtensionProvider(rollingSigner, credentialScope)); break; } case STREAMING_UNSIGNED_PAYLOAD_TRAILER: setupChecksumTrailerIfNeeded(chunkedEncodedInputStreamBuilder); break; case STREAMING_SIGNED_PAYLOAD_TRAILER: { RollingSigner rollingSigner = new RollingSigner(requestSigningResult.getSigningKey(), requestSigningResult.getSignature()); chunkedEncodedInputStreamBuilder.addExtension(new SigV4ChunkExtensionProvider(rollingSigner, credentialScope)); setupChecksumTrailerIfNeeded(chunkedEncodedInputStreamBuilder); chunkedEncodedInputStreamBuilder.addTrailer( new SigV4TrailerProvider(chunkedEncodedInputStreamBuilder.trailers(), rollingSigner, credentialScope) ); break; } default: throw new UnsupportedOperationException(); } return new ResettableContentStreamProvider(chunkedEncodedInputStreamBuilder::build); } @Override public Publisher<ByteBuffer> signAsync(Publisher<ByteBuffer> payload, V4RequestSigningResult requestSigningResult) { throw new UnsupportedOperationException(); } @Override public void beforeSigning(SdkHttpRequest.Builder request, ContentStreamProvider payload) { long encodedContentLength = 0; long contentLength = moveContentLength(request, payload != null ? payload.newStream() : new StringInputStream("")); setupPreExistingTrailers(request); // pre-existing trailers encodedContentLength += calculateExistingTrailersLength(); String checksum = request.firstMatchingHeader(X_AMZ_CONTENT_SHA256).orElseThrow( () -> new IllegalArgumentException(X_AMZ_CONTENT_SHA256 + " must be set!") ); switch (checksum) { case STREAMING_SIGNED_PAYLOAD: { long extensionsLength = 81; // ;chunk-signature:<sigv4 hex signature, 64 bytes> encodedContentLength += calculateChunksLength(contentLength, extensionsLength); break; } case STREAMING_UNSIGNED_PAYLOAD_TRAILER: if (checksumAlgorithm != null) { encodedContentLength += calculateChecksumTrailerLength(checksumHeaderName(checksumAlgorithm)); } encodedContentLength += calculateChunksLength(contentLength, 0); break; case STREAMING_SIGNED_PAYLOAD_TRAILER: { long extensionsLength = 81; // ;chunk-signature:<sigv4 hex signature, 64 bytes> encodedContentLength += calculateChunksLength(contentLength, extensionsLength); if (checksumAlgorithm != null) { encodedContentLength += calculateChecksumTrailerLength(checksumHeaderName(checksumAlgorithm)); } encodedContentLength += 90; // x-amz-trailer-signature:<sigv4 hex signature, 64 bytes>\r\n break; } default: throw new UnsupportedOperationException(); } // terminating \r\n encodedContentLength += 2; if (checksumAlgorithm != null) { String checksumHeaderName = checksumHeaderName(checksumAlgorithm); request.appendHeader(X_AMZ_TRAILER, checksumHeaderName); } request.putHeader(Header.CONTENT_LENGTH, Long.toString(encodedContentLength)); request.appendHeader(CONTENT_ENCODING, AWS_CHUNKED); } /** * Set up a map of pre-existing trailer (headers) for the given request to be used when chunk-encoding the payload. * <p> * However, we need to validate that these are valid trailers. Since aws-chunked encoding adds the checksum as a trailer, it * isn't part of the request headers, but other trailers MUST be present in the request-headers. */ private void setupPreExistingTrailers(SdkHttpRequest.Builder request) { for (String header : request.matchingHeaders(X_AMZ_TRAILER)) { List<String> values = request.matchingHeaders(header); if (values.isEmpty()) { throw new IllegalArgumentException(header + " must be present in the request headers to be a valid trailer."); } preExistingTrailers.add(Pair.of(header, values)); request.removeHeader(header); } } private long calculateChunksLength(long contentLength, long extensionsLength) { long lengthInBytes = 0; long chunkHeaderLength = Integer.toHexString(chunkSize).length(); long numChunks = contentLength / chunkSize; // normal chunks // x<metadata>\r\n<data>\r\n lengthInBytes += numChunks * (chunkHeaderLength + extensionsLength + 2 + chunkSize + 2); // remaining chunk // x<metadata>\r\n<data>\r\n long remainingBytes = contentLength % chunkSize; if (remainingBytes > 0) { long remainingChunkHeaderLength = Long.toHexString(remainingBytes).length(); lengthInBytes += remainingChunkHeaderLength + extensionsLength + 2 + remainingBytes + 2; } // final chunk // 0<metadata>\r\n lengthInBytes += 1 + extensionsLength + 2; return lengthInBytes; } private long calculateExistingTrailersLength() { long lengthInBytes = 0; for (Pair<String, List<String>> trailer : preExistingTrailers) { // size of trailer lengthInBytes += calculateTrailerLength(trailer); } return lengthInBytes; } private long calculateTrailerLength(Pair<String, List<String>> trailer) { // size of trailer-header and colon long lengthInBytes = trailer.left().length() + 1L; // size of trailer-values for (String value : trailer.right()) { lengthInBytes += value.length(); } // size of commas between trailer-values, 1 less comma than # of values lengthInBytes += trailer.right().size() - 1; // terminating \r\n return lengthInBytes + 2; } private long calculateChecksumTrailerLength(String checksumHeaderName) { // size of checksum trailer-header and colon long lengthInBytes = checksumHeaderName.length() + 1L; // get the base checksum for the algorithm SdkChecksum sdkChecksum = fromChecksumAlgorithm(checksumAlgorithm); // size of checksum value as encoded-string lengthInBytes += BinaryUtils.toBase64(sdkChecksum.getChecksumBytes()).length(); // terminating \r\n return lengthInBytes + 2; } /** * Add the checksum as a trailer to the chunk-encoded stream. * <p> * If the checksum-algorithm is not present, then nothing is done. */ private void setupChecksumTrailerIfNeeded(ChunkedEncodedInputStream.Builder builder) { if (checksumAlgorithm == null) { return; } String checksumHeaderName = checksumHeaderName(checksumAlgorithm); SdkChecksum sdkChecksum = fromChecksumAlgorithm(checksumAlgorithm); ChecksumInputStream checksumInputStream = new ChecksumInputStream( builder.inputStream(), Collections.singleton(sdkChecksum) ); TrailerProvider checksumTrailer = new ChecksumTrailerProvider(sdkChecksum, checksumHeaderName); builder.inputStream(checksumInputStream).addTrailer(checksumTrailer); } static class Builder { private CredentialScope credentialScope; private Integer chunkSize; private ChecksumAlgorithm checksumAlgorithm; public Builder credentialScope(CredentialScope credentialScope) { this.credentialScope = credentialScope; return this; } public Builder chunkSize(Integer chunkSize) { this.chunkSize = chunkSize; return this; } public Builder checksumAlgorithm(ChecksumAlgorithm checksumAlgorithm) { this.checksumAlgorithm = checksumAlgorithm; return this; } public AwsChunkedV4PayloadSigner build() { return new AwsChunkedV4PayloadSigner(this); } } }
2,592
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal/signer
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal/signer/util/OptionalDependencyLoaderUtil.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.signer.util; import java.time.Clock; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.auth.aws.crt.internal.signer.DefaultAwsCrtV4aHttpSigner; import software.amazon.awssdk.http.auth.aws.eventstream.internal.signer.EventStreamV4PayloadSigner; import software.amazon.awssdk.http.auth.aws.internal.signer.CredentialScope; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.utils.ClassLoaderHelper; import software.amazon.awssdk.utils.Logger; /** * Utilities for loading of classes and objects which have optional dependencies, and therefore need to be safely checked at * runtime in order to use. */ @SdkInternalApi public final class OptionalDependencyLoaderUtil { private static final Logger LOG = Logger.loggerFor(OptionalDependencyLoaderUtil.class); private static final String HTTP_AUTH_AWS_CRT_PATH = "software.amazon.awssdk.http.auth.aws.crt.HttpAuthAwsCrt"; private static final String HTTP_AUTH_AWS_CRT_MODULE = "software.amazon.awssdk:http-auth-aws-crt"; private static final String HTTP_AUTH_AWS_EVENT_STREAM_PATH = "software.amazon.awssdk.http.auth.aws.eventstream.HttpAuthAwsEventStream"; private static final String HTTP_AUTH_AWS_EVENT_STREAM_MODULE = "software.amazon.awssdk:http-auth-aws-eventstream"; private OptionalDependencyLoaderUtil() { } /** * A helpful method that checks that some class is available on the class-path. If it fails to load, it will throw an * exception based on why it failed to load. This should be used in cases where certain dependencies are optional, but the * dependency is used at compile-time for strong typing (i.e. {@link EventStreamV4PayloadSigner}). */ private static void requireClass(String classPath, String module, String feature) { try { ClassLoaderHelper.loadClass(classPath, false); } catch (ClassNotFoundException e) { LOG.debug(() -> "Cannot find the " + classPath + " class: ", e); String msg = String.format("Could not load class. You must add a dependency on the '%s' module to enable the %s " + "feature: ", module, feature); throw new RuntimeException(msg, e); } catch (Exception e) { throw new RuntimeException(String.format("Could not load class (%s): ", classPath), e); } } public static DefaultAwsCrtV4aHttpSigner getDefaultAwsCrtV4aHttpSigner() { requireClass(HTTP_AUTH_AWS_CRT_PATH, HTTP_AUTH_AWS_CRT_MODULE, "CRT-V4a signing"); return new DefaultAwsCrtV4aHttpSigner(); } public static EventStreamV4PayloadSigner getEventStreamV4PayloadSigner( AwsCredentialsIdentity credentials, CredentialScope credentialScope, Clock signingClock) { requireClass(HTTP_AUTH_AWS_EVENT_STREAM_PATH, HTTP_AUTH_AWS_EVENT_STREAM_MODULE, "Event-stream signing"); return EventStreamV4PayloadSigner.builder() .credentials(credentials) .credentialScope(credentialScope) .signingClock(signingClock) .build(); } }
2,593
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal/signer
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal/signer/util/SigningAlgorithm.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.signer.util; import java.security.NoSuchAlgorithmException; import javax.crypto.Mac; import software.amazon.awssdk.annotations.SdkInternalApi; @SdkInternalApi public enum SigningAlgorithm { HMAC_SHA256("HmacSHA256"); private final String algorithmName; private final ThreadLocal<Mac> macReference; SigningAlgorithm(String algorithmName) { this.algorithmName = algorithmName; macReference = new MacThreadLocal(algorithmName); } public String getAlgorithmName() { return algorithmName; } /** * Returns the thread local reference for the crypto algorithm */ public Mac getMac() { return macReference.get(); } private static class MacThreadLocal extends ThreadLocal<Mac> { private final String algorithmName; MacThreadLocal(String algorithmName) { this.algorithmName = algorithmName; } @Override protected Mac initialValue() { try { return Mac.getInstance(algorithmName); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Unable to fetch Mac instance for Algorithm " + algorithmName + ": " + e.getMessage()); } } } }
2,594
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal/signer
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal/signer/util/BoundedLinkedHashMap.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.signer.util; import java.util.LinkedHashMap; import java.util.Map; import software.amazon.awssdk.annotations.SdkInternalApi; /** * A bounded linked hash map that would remove the eldest entry when the map size exceeds a configurable maximum. */ @SdkInternalApi final class BoundedLinkedHashMap<K, V> extends LinkedHashMap<K, V> { private static final long serialVersionUID = 1L; private final int maxSize; BoundedLinkedHashMap(int maxSize) { this.maxSize = maxSize; } /** * {@inheritDoc} * <p> * Returns true if the size of this map exceeds the maximum. */ @Override protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return size() > maxSize; } /** * Returns the maximum size of this map beyond which the eldest entry will get removed. */ int getMaxSize() { return maxSize; } }
2,595
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal/signer
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal/signer/util/FifoCache.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.signer.util; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock; import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.ThreadSafe; /** * A bounded cache that has a FIFO eviction policy when the cache is full. * * @param <T> value type */ @ThreadSafe @SdkInternalApi public final class FifoCache<T> { private final BoundedLinkedHashMap<String, T> map; private final ReadLock rlock; private final WriteLock wlock; /** * @param maxSize the maximum number of entries of the cache */ public FifoCache(int maxSize) { if (maxSize < 1) { throw new IllegalArgumentException("maxSize " + maxSize + " must be at least 1"); } map = new BoundedLinkedHashMap<>(maxSize); ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); rlock = lock.readLock(); wlock = lock.writeLock(); } /** * Adds an entry to the cache, evicting the earliest entry if necessary. */ public T add(String key, T value) { wlock.lock(); try { return map.put(key, value); } finally { wlock.unlock(); } } /** * Returns the value of the given key; or null of no such entry exists. */ public T get(String key) { rlock.lock(); try { return map.get(key); } finally { rlock.unlock(); } } /** * Returns the current size of the cache. */ public int size() { rlock.lock(); try { return map.size(); } finally { rlock.unlock(); } } /** * Returns the maximum size of the cache. */ public int getMaxSize() { return map.getMaxSize(); } @Override public String toString() { rlock.lock(); try { return map.toString(); } finally { rlock.unlock(); } } }
2,596
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal/signer
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal/signer/util/DigestAlgorithm.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.signer.util; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import software.amazon.awssdk.annotations.SdkInternalApi; @SdkInternalApi public enum DigestAlgorithm { SHA1("SHA-1"), MD5("MD5"), SHA256("SHA-256") ; private final String algorithmName; private final DigestThreadLocal digestReference; DigestAlgorithm(String algorithmName) { this.algorithmName = algorithmName; digestReference = new DigestThreadLocal(algorithmName); } public String getAlgorithmName() { return algorithmName; } /** * Returns the thread local reference for the {@link MessageDigest} algorithm */ public MessageDigest getDigest() { MessageDigest digest = digestReference.get(); digest.reset(); return digest; } private static class DigestThreadLocal extends ThreadLocal<MessageDigest> { private final String algorithmName; DigestThreadLocal(String algorithmName) { this.algorithmName = algorithmName; } @Override protected MessageDigest initialValue() { try { return MessageDigest.getInstance(algorithmName); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Unable to fetch message digest instance for Algorithm " + algorithmName + ": " + e.getMessage(), e); } } } }
2,597
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal/signer
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal/signer/util/ChecksumUtil.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.signer.util; import static software.amazon.awssdk.checksums.DefaultChecksumAlgorithm.CRC32; import static software.amazon.awssdk.checksums.DefaultChecksumAlgorithm.CRC32C; import static software.amazon.awssdk.checksums.DefaultChecksumAlgorithm.MD5; import static software.amazon.awssdk.checksums.DefaultChecksumAlgorithm.SHA1; import static software.amazon.awssdk.checksums.DefaultChecksumAlgorithm.SHA256; import java.io.InputStream; import java.util.Locale; import java.util.Map; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.checksums.spi.ChecksumAlgorithm; import software.amazon.awssdk.http.auth.aws.internal.signer.checksums.ConstantChecksum; import software.amazon.awssdk.http.auth.aws.internal.signer.checksums.Crc32CChecksum; import software.amazon.awssdk.http.auth.aws.internal.signer.checksums.Crc32Checksum; import software.amazon.awssdk.http.auth.aws.internal.signer.checksums.Md5Checksum; import software.amazon.awssdk.http.auth.aws.internal.signer.checksums.SdkChecksum; import software.amazon.awssdk.http.auth.aws.internal.signer.checksums.Sha1Checksum; import software.amazon.awssdk.http.auth.aws.internal.signer.checksums.Sha256Checksum; import software.amazon.awssdk.utils.ImmutableMap; @SdkInternalApi public final class ChecksumUtil { private static final String CONSTANT_CHECKSUM = "CONSTANT"; private static final Map<String, Supplier<SdkChecksum>> CHECKSUM_MAP = ImmutableMap.of( SHA256.algorithmId(), Sha256Checksum::new, SHA1.algorithmId(), Sha1Checksum::new, CRC32.algorithmId(), Crc32Checksum::new, CRC32C.algorithmId(), Crc32CChecksum::new, MD5.algorithmId(), Md5Checksum::new ); private ChecksumUtil() { } /** * Get the correct checksum header name based on the checksum-algorithm. This is required to be of the form * {@code x-amz-checksum-*}, where '*' is alphanumeric checksum-algorithm-id in lower-case form. Examples include: * <p> * x-amz-checksum-sha256, x-amz-checksum-sha1, x-amz-checksum-crc32, x-amz-checksum-crc32c, x-amz-checksum-md5 * </p> */ public static String checksumHeaderName(ChecksumAlgorithm checksumAlgorithm) { return "x-amz-checksum-" + checksumAlgorithm.algorithmId().toLowerCase(Locale.US); } /** * Gets the SdkChecksum object based on the given ChecksumAlgorithm. */ public static SdkChecksum fromChecksumAlgorithm(ChecksumAlgorithm checksumAlgorithm) { String algorithmId = checksumAlgorithm.algorithmId(); Supplier<SdkChecksum> checksumSupplier = CHECKSUM_MAP.get(algorithmId); if (checksumSupplier != null) { return checksumSupplier.get(); } if (CONSTANT_CHECKSUM.equals(algorithmId)) { return new ConstantChecksum(((ConstantChecksumAlgorithm) checksumAlgorithm).value); } throw new UnsupportedOperationException("Checksum not supported for " + algorithmId); } /** * Read the entirety of an input-stream - this is useful when the stream has side-effects (such as calculating a checksum) * when it gets read. */ public static void readAll(InputStream inputStream) { try { byte[] buffer = new byte[4096]; while (inputStream.read(buffer) > -1) { } } catch (Exception e) { throw new RuntimeException("Could not finish reading stream: ", e); } } /** * An implementation of a {@link ChecksumAlgorithm} that will map to {@link ConstantChecksum}, which provides a constant * checksum. This isn't super useful, but is needed in cases such as signing, where the content-hash (a * cryptographically-secure "checksum") can be a set of pre-defined values. */ public static class ConstantChecksumAlgorithm implements ChecksumAlgorithm { private final String value; public ConstantChecksumAlgorithm(String value) { this.value = value; } @Override public String algorithmId() { return CONSTANT_CHECKSUM; } } }
2,598
0
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal/signer
Create_ds/aws-sdk-java-v2/core/http-auth-aws/src/main/java/software/amazon/awssdk/http/auth/aws/internal/signer/util/SignerKey.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.signer.util; import java.time.Instant; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.utils.DateUtils; /** * Holds the signing key and the number of days since epoch for the date for which the signing key was generated. */ @Immutable @SdkInternalApi public final class SignerKey { private final long daysSinceEpoch; private final byte[] signingKey; public SignerKey(Instant date, byte[] signingKey) { if (date == null) { throw new IllegalArgumentException( "Not able to cache signing key. Signing date to be is null"); } if (signingKey == null) { throw new IllegalArgumentException( "Not able to cache signing key. Signing Key to be cached are null"); } this.daysSinceEpoch = DateUtils.numberOfDaysSinceEpoch(date.toEpochMilli()); this.signingKey = signingKey.clone(); } public boolean isValidForDate(Instant other) { return daysSinceEpoch == DateUtils.numberOfDaysSinceEpoch(other.toEpochMilli()); } /** * Returns a copy of the signing key. */ public byte[] getSigningKey() { return signingKey.clone(); } }
2,599