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/regions/src/main/java/software/amazon/awssdk/regions
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/util/HttpResourcesUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.util; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URI; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.protocols.jsoncore.JsonNode; import software.amazon.awssdk.protocols.jsoncore.JsonNodeParser; import software.amazon.awssdk.regions.internal.util.ConnectionUtils; import software.amazon.awssdk.utils.IoUtils; @SdkProtectedApi public final class HttpResourcesUtils { private static final Logger log = LoggerFactory.getLogger(HttpResourcesUtils.class); private static final JsonNodeParser JSON_PARSER = JsonNode.parser(); private static volatile HttpResourcesUtils instance; private final ConnectionUtils connectionUtils; private HttpResourcesUtils() { this(ConnectionUtils.create()); } HttpResourcesUtils(ConnectionUtils connectionUtils) { this.connectionUtils = connectionUtils; } public static HttpResourcesUtils instance() { if (instance == null) { synchronized (HttpResourcesUtils.class) { if (instance == null) { instance = new HttpResourcesUtils(); } } } return instance; } /** * Connects to the given endpoint to read the resource * and returns the text contents. * * If the connection fails, the request will not be retried. * * @param endpoint The service endpoint to connect to. * @return The text payload returned from the container metadata endpoint * service for the specified resource path. * @throws IOException If any problems were encountered while connecting to the * service for the requested resource path. * @throws SdkClientException If the requested service is not found. */ public String readResource(URI endpoint) throws IOException { return readResource(() -> endpoint, "GET"); } /** * Connects to the given endpoint to read the resource * and returns the text contents. * * @param endpointProvider The endpoint provider. * @return The text payload returned from the container metadata endpoint * service for the specified resource path. * @throws IOException If any problems were encountered while connecting to the * service for the requested resource path. * @throws SdkClientException If the requested service is not found. */ public String readResource(ResourcesEndpointProvider endpointProvider) throws IOException { return readResource(endpointProvider, "GET"); } /** * Connects to the given endpoint to read the resource * and returns the text contents. * * @param endpointProvider The endpoint provider. * @param method The HTTP request method to use. * @return The text payload returned from the container metadata endpoint * service for the specified resource path. * @throws IOException If any problems were encountered while connecting to the * service for the requested resource path. * @throws SdkClientException If the requested service is not found. */ public String readResource(ResourcesEndpointProvider endpointProvider, String method) throws IOException { int retriesAttempted = 0; InputStream inputStream = null; while (true) { try { HttpURLConnection connection = connectionUtils.connectToEndpoint(endpointProvider.endpoint(), endpointProvider.headers(), method); int statusCode = connection.getResponseCode(); if (statusCode == HttpURLConnection.HTTP_OK) { inputStream = connection.getInputStream(); return IoUtils.toUtf8String(inputStream); } else if (statusCode == HttpURLConnection.HTTP_NOT_FOUND) { // This is to preserve existing behavior of EC2 Instance metadata service. throw SdkClientException.builder() .message("The requested metadata is not found at " + connection.getURL()) .build(); } else { if (!endpointProvider.retryPolicy().shouldRetry(retriesAttempted++, ResourcesEndpointRetryParameters.builder() .withStatusCode(statusCode) .build())) { inputStream = connection.getErrorStream(); handleErrorResponse(inputStream, statusCode, connection.getResponseMessage()); } } } catch (IOException ioException) { if (!endpointProvider.retryPolicy().shouldRetry(retriesAttempted++, ResourcesEndpointRetryParameters.builder() .withException(ioException) .build())) { throw ioException; } log.debug("An IOException occurred when connecting to endpoint: {} \n Retrying to connect again", endpointProvider.endpoint()); } finally { IoUtils.closeQuietly(inputStream, log); } } } private void handleErrorResponse(InputStream errorStream, int statusCode, String responseMessage) throws IOException { // Parse the error stream returned from the service. if (errorStream != null) { String errorResponse = IoUtils.toUtf8String(errorStream); try { Optional<JsonNode> message = JSON_PARSER.parse(errorResponse).field("message"); if (message.isPresent()) { responseMessage = message.get().text(); } } catch (RuntimeException exception) { log.debug("Unable to parse error stream", exception); } } throw SdkServiceException.builder() .message(responseMessage) .statusCode(statusCode) .build(); } }
1,600
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/providers/AwsRegionProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.providers; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.regions.Region; /** * Interface for providing AWS region information. Implementations are free to use any strategy for * providing region information. */ @SdkProtectedApi @FunctionalInterface public interface AwsRegionProvider { /** * Returns the region name to use. If region information is not available, throws an {@link SdkClientException}. * * @return Region name to use. */ Region getRegion(); }
1,601
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/providers/InstanceProfileRegionProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.providers; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.internal.util.EC2MetadataUtils; /** * Attempts to load region information from the EC2 Metadata service. If the application is not * running on EC2 this provider will thrown an exception. * * <P> * If {@link SdkSystemSetting#AWS_EC2_METADATA_DISABLED} is set to true, it will not try to load * region from EC2 metadata service and will return null. */ @SdkProtectedApi public final class InstanceProfileRegionProvider implements AwsRegionProvider { /** * Cache region as it will not change during the lifetime of the JVM. */ private volatile String region; @Override public Region getRegion() throws SdkClientException { if (SdkSystemSetting.AWS_EC2_METADATA_DISABLED.getBooleanValueOrThrow()) { throw SdkClientException.builder() .message("EC2 Metadata is disabled. Unable to retrieve region information from " + "EC2 Metadata service.") .build(); } if (region == null) { synchronized (this) { if (region == null) { this.region = tryDetectRegion(); } } } if (region == null) { throw SdkClientException.builder() .message("Unable to retrieve region information from EC2 Metadata service. " + "Please make sure the application is running on EC2.") .build(); } return Region.of(region); } private String tryDetectRegion() { return EC2MetadataUtils.getEC2InstanceRegion(); } }
1,602
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/providers/AwsProfileRegionProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.providers; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileFileSystemSetting; import software.amazon.awssdk.profiles.ProfileProperty; import software.amazon.awssdk.regions.Region; /** * Loads region information from the {@link ProfileFile#defaultProfileFile()} using the default profile name. */ @SdkProtectedApi public final class AwsProfileRegionProvider implements AwsRegionProvider { private final Supplier<ProfileFile> profileFile; private final String profileName; public AwsProfileRegionProvider() { this(null, null); } public AwsProfileRegionProvider(Supplier<ProfileFile> profileFile, String profileName) { this.profileFile = profileFile != null ? profileFile : ProfileFile::defaultProfileFile; this.profileName = profileName != null ? profileName : ProfileFileSystemSetting.AWS_PROFILE.getStringValueOrThrow(); } @Override public Region getRegion() { return profileFile.get() .profile(profileName) .map(p -> p.properties().get(ProfileProperty.REGION)) .map(Region::of) .orElseThrow(() -> SdkClientException.builder() .message("No region provided in profile: " + profileName) .build()); } }
1,603
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/providers/DefaultAwsRegionProviderChain.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.providers; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.profiles.ProfileFile; /** * AWS Region provider that looks for the region in this order: * <ol> * <li>Check the 'aws.region' system property for the region.</li> * <li>Check the 'AWS_REGION' environment variable for the region.</li> * <li>Check the {user.home}/.aws/credentials and {user.home}/.aws/config files for the region.</li> * <li>If running in EC2, check the EC2 metadata service for the region.</li> * </ol> */ @SdkProtectedApi public final class DefaultAwsRegionProviderChain extends AwsRegionProviderChain { public DefaultAwsRegionProviderChain() { super(new SystemSettingsRegionProvider(), new AwsProfileRegionProvider(), new InstanceProfileRegionProvider()); } private DefaultAwsRegionProviderChain(Builder builder) { super(new SystemSettingsRegionProvider(), new AwsProfileRegionProvider(builder.profileFile, builder.profileName), new InstanceProfileRegionProvider()); } public static Builder builder() { return new Builder(); } public static final class Builder { private Supplier<ProfileFile> profileFile; private String profileName; private Builder() { } public Builder profileFile(Supplier<ProfileFile> profileFile) { this.profileFile = profileFile; return this; } public Builder profileName(String profileName) { this.profileName = profileName; return this; } public DefaultAwsRegionProviderChain build() { return new DefaultAwsRegionProviderChain(this); } } }
1,604
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/providers/SystemSettingsRegionProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.providers; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.regions.Region; /** * Loads region information from the 'aws.region' system property or the 'AWS_REGION' environment variable. If both are specified, * the system property will be used. */ @SdkProtectedApi public final class SystemSettingsRegionProvider implements AwsRegionProvider { @Override public Region getRegion() throws SdkClientException { return SdkSystemSetting.AWS_REGION.getStringValue() .map(Region::of) .orElseThrow(this::exception); } private SdkClientException exception() { return SdkClientException.builder().message(String.format("Unable to load region from system settings. Region" + " must be specified either via environment variable (%s) or " + " system property (%s).", SdkSystemSetting.AWS_REGION.environmentVariable(), SdkSystemSetting.AWS_REGION.property())).build(); } }
1,605
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/providers/LazyAwsRegionProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.providers; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.utils.Lazy; import software.amazon.awssdk.utils.ToString; /** * A wrapper for {@link AwsRegionProvider} that defers creation of the underlying provider until the first time the * {@link AwsRegionProvider#getRegion()} method is invoked. */ @SdkProtectedApi public class LazyAwsRegionProvider implements AwsRegionProvider { private final Lazy<AwsRegionProvider> delegate; public LazyAwsRegionProvider(Supplier<AwsRegionProvider> delegateConstructor) { this.delegate = new Lazy<>(delegateConstructor); } @Override public Region getRegion() { return delegate.getValue().getRegion(); } @Override public String toString() { return ToString.builder("LazyAwsRegionProvider") .add("delegate", delegate) .build(); } }
1,606
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/providers/AwsRegionProviderChain.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.providers; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.regions.Region; /** * Composite {@link AwsRegionProvider} that sequentially delegates to a chain of providers looking * for region information. * * Throws an {@link SdkClientException} if region could not be find in any of the providers. */ @SdkProtectedApi public class AwsRegionProviderChain implements AwsRegionProvider { private static final Logger log = LoggerFactory.getLogger(AwsRegionProviderChain.class); private final List<AwsRegionProvider> providers; public AwsRegionProviderChain(AwsRegionProvider... providers) { this.providers = new ArrayList<>(providers.length); Collections.addAll(this.providers, providers); } @Override public Region getRegion() throws SdkClientException { List<String> exceptionMessages = null; for (AwsRegionProvider provider : providers) { try { Region region = provider.getRegion(); if (region != null) { return region; } } catch (Exception e) { // Ignore any exceptions and move onto the next provider log.debug("Unable to load region from {}:{}", provider.toString(), e.getMessage()); String message = provider.toString() + ": " + e.getMessage(); if (exceptionMessages == null) { exceptionMessages = new ArrayList<>(); } exceptionMessages.add(message); } } throw SdkClientException.builder() .message("Unable to load region from any of the providers in the chain " + this + ": " + exceptionMessages) .build(); } }
1,607
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/internal/MetadataLoader.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.internal; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.regions.GeneratedPartitionMetadataProvider; import software.amazon.awssdk.regions.GeneratedRegionMetadataProvider; import software.amazon.awssdk.regions.GeneratedServiceMetadataProvider; import software.amazon.awssdk.regions.PartitionMetadata; import software.amazon.awssdk.regions.PartitionMetadataProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.RegionMetadata; import software.amazon.awssdk.regions.RegionMetadataProvider; import software.amazon.awssdk.regions.ServiceMetadata; import software.amazon.awssdk.regions.ServiceMetadataProvider; /** * Internal class for determining where to load region and service * metadata from. Currently only generated region metadata is supported. */ @SdkInternalApi public final class MetadataLoader { private static final RegionMetadataProvider REGION_METADATA_PROVIDER = new GeneratedRegionMetadataProvider(); private static final ServiceMetadataProvider SERVICE_METADATA_PROVIDER = new GeneratedServiceMetadataProvider(); private static final PartitionMetadataProvider PARTITION_METADATA_PROVIDER = new GeneratedPartitionMetadataProvider(); private MetadataLoader() { } public static PartitionMetadata partitionMetadata(Region region) { return PARTITION_METADATA_PROVIDER.partitionMetadata(region); } public static PartitionMetadata partitionMetadata(String partition) { return PARTITION_METADATA_PROVIDER.partitionMetadata(partition); } public static RegionMetadata regionMetadata(Region region) { return REGION_METADATA_PROVIDER.regionMetadata(region); } public static ServiceMetadata serviceMetadata(String service) { return SERVICE_METADATA_PROVIDER.serviceMetadata(service); } }
1,608
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/internal/DefaultServicePartitionMetadata.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.internal; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.regions.PartitionMetadata; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.ServicePartitionMetadata; @SdkInternalApi public class DefaultServicePartitionMetadata implements ServicePartitionMetadata { private final String partition; private final Region globalRegionForPartition; public DefaultServicePartitionMetadata(String partition, Region globalRegionForPartition) { this.partition = partition; this.globalRegionForPartition = globalRegionForPartition; } @Override public PartitionMetadata partition() { return PartitionMetadata.of(partition); } @Override public Optional<Region> globalRegion() { return Optional.ofNullable(globalRegionForPartition); } }
1,609
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/internal
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/internal/util/ConnectionUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.internal.util; import java.io.IOException; import java.net.HttpURLConnection; import java.net.Proxy; import java.net.URI; import java.util.Map; import software.amazon.awssdk.annotations.SdkInternalApi; @SdkInternalApi //TODO: Refactor to use SDK HTTP client instead of URL connection, also consider putting EC2MetadataClient in its own module public class ConnectionUtils { public static ConnectionUtils create() { return new ConnectionUtils(); } public HttpURLConnection connectToEndpoint(URI endpoint, Map<String, String> headers) throws IOException { return connectToEndpoint(endpoint, headers, "GET"); } public HttpURLConnection connectToEndpoint(URI endpoint, Map<String, String> headers, String method) throws IOException { HttpURLConnection connection = (HttpURLConnection) endpoint.toURL().openConnection(Proxy.NO_PROXY); connection.setConnectTimeout(1000); connection.setReadTimeout(1000); connection.setRequestMethod(method); connection.setDoOutput(true); headers.forEach(connection::addRequestProperty); connection.setInstanceFollowRedirects(false); connection.connect(); return connection; } }
1,610
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/internal
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/internal/util/Ec2MetadataConfigProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.internal.util; import java.util.Optional; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.profiles.Profile; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileFileSystemSetting; import software.amazon.awssdk.profiles.ProfileProperty; @SdkInternalApi // TODO: Remove or consolidate this class with the one from the auth module. // There's currently no good way for both auth and regions to share the same // class since there's no suitable common dependency between the two where this // can live. Ideally, we can do this when the EC2MetadataUtils is replaced with // the IMDS client. public final class Ec2MetadataConfigProvider { /** Default IPv4 endpoint for the Amazon EC2 Instance Metadata Service. */ private static final String EC2_METADATA_SERVICE_URL_IPV4 = "http://169.254.169.254"; /** Default IPv6 endpoint for the Amazon EC2 Instance Metadata Service. */ private static final String EC2_METADATA_SERVICE_URL_IPV6 = "http://[fd00:ec2::254]"; private final Supplier<ProfileFile> profileFile; private final String profileName; private Ec2MetadataConfigProvider(Builder builder) { this.profileFile = builder.profileFile; this.profileName = builder.profileName; } public enum EndpointMode { IPV4, IPV6, ; public static EndpointMode fromValue(String s) { if (s == null) { return null; } for (EndpointMode value : EndpointMode.values()) { if (value.name().equalsIgnoreCase(s)) { return value; } } throw new IllegalArgumentException("Unrecognized value for endpoint mode: " + s); } } public String getEndpoint() { String endpointOverride = getEndpointOverride(); if (endpointOverride != null) { return endpointOverride; } EndpointMode endpointMode = getEndpointMode(); switch (endpointMode) { case IPV4: return EC2_METADATA_SERVICE_URL_IPV4; case IPV6: return EC2_METADATA_SERVICE_URL_IPV6; default: throw SdkClientException.create("Unknown endpoint mode: " + endpointMode); } } public EndpointMode getEndpointMode() { Optional<String> endpointMode = SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE.getNonDefaultStringValue(); if (endpointMode.isPresent()) { return EndpointMode.fromValue(endpointMode.get()); } return configFileEndpointMode().orElseGet(() -> EndpointMode.fromValue(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE.defaultValue())); } public String getEndpointOverride() { Optional<String> endpointOverride = SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.getNonDefaultStringValue(); if (endpointOverride.isPresent()) { return endpointOverride.get(); } Optional<String> configFileValue = configFileEndpointOverride(); return configFileValue.orElse(null); } public static Builder builder() { return new Builder(); } private Optional<EndpointMode> configFileEndpointMode() { return resolveProfile().flatMap(p -> p.property(ProfileProperty.EC2_METADATA_SERVICE_ENDPOINT_MODE)) .map(EndpointMode::fromValue); } private Optional<String> configFileEndpointOverride() { return resolveProfile().flatMap(p -> p.property(ProfileProperty.EC2_METADATA_SERVICE_ENDPOINT)); } private Optional<Profile> resolveProfile() { ProfileFile profileFileToUse = resolveProfileFile(); String profileNameToUse = resolveProfileName(); return profileFileToUse.profile(profileNameToUse); } private ProfileFile resolveProfileFile() { if (profileFile != null) { return profileFile.get(); } return ProfileFile.defaultProfileFile(); } private String resolveProfileName() { if (profileName != null) { return profileName; } return ProfileFileSystemSetting.AWS_PROFILE.getStringValueOrThrow(); } public static class Builder { private Supplier<ProfileFile> profileFile; private String profileName; public Builder profileFile(Supplier<ProfileFile> profileFile) { this.profileFile = profileFile; return this; } public Builder profileName(String profileName) { this.profileName = profileName; return this; } public Ec2MetadataConfigProvider build() { return new Ec2MetadataConfigProvider(this); } } }
1,611
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/internal
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/internal/util/EC2MetadataUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.internal.util; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkTestInternalApi; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.core.util.SdkUserAgent; import software.amazon.awssdk.protocols.jsoncore.JsonNode; import software.amazon.awssdk.protocols.jsoncore.JsonNodeParser; import software.amazon.awssdk.regions.util.HttpResourcesUtils; import software.amazon.awssdk.regions.util.ResourcesEndpointProvider; /** * * Utility class for retrieving Amazon EC2 instance metadata. * * <p> * <b>Note</b>: this is an internal API subject to change. Users of the SDK * should not depend on this. * * <p> * You can use the data to build more generic AMIs that can be modified by * configuration files supplied at launch time. For example, if you run web * servers for various small businesses, they can all use the same AMI and * retrieve their content from the Amazon S3 bucket you specify at launch. To * add a new customer at any time, simply create a bucket for the customer, add * their content, and launch your AMI.<br> * * <P> * If {@link SdkSystemSetting#AWS_EC2_METADATA_DISABLED} is set to true, EC2 metadata usage * will be disabled and {@link SdkClientException} will be thrown for any metadata retrieval attempt. * * <p> * More information about Amazon EC2 Metadata * * @see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AESDG-chapter-instancedata.html">Amazon * EC2 User Guide: Instance Metadata</a> */ @SdkInternalApi public final class EC2MetadataUtils { private static final JsonNodeParser JSON_PARSER = JsonNode.parser(); /** Default resource path for credentials in the Amazon EC2 Instance Metadata Service. */ private static final String REGION = "region"; private static final String INSTANCE_IDENTITY_DOCUMENT = "instance-identity/document"; private static final String INSTANCE_IDENTITY_SIGNATURE = "instance-identity/signature"; private static final String EC2_METADATA_ROOT = "/latest/meta-data"; private static final String EC2_USERDATA_ROOT = "/latest/user-data/"; private static final String EC2_DYNAMICDATA_ROOT = "/latest/dynamic/"; private static final String EC2_METADATA_TOKEN_HEADER = "x-aws-ec2-metadata-token"; private static final int DEFAULT_QUERY_ATTEMPTS = 3; private static final int MINIMUM_RETRY_WAIT_TIME_MILLISECONDS = 250; private static final Logger log = LoggerFactory.getLogger(EC2MetadataUtils.class); private static final Map<String, String> CACHE = new ConcurrentHashMap<>(); private static final InstanceProviderTokenEndpointProvider TOKEN_ENDPOINT_PROVIDER = new InstanceProviderTokenEndpointProvider(); private static final Ec2MetadataConfigProvider EC2_METADATA_CONFIG_PROVIDER = Ec2MetadataConfigProvider.builder() .build(); private EC2MetadataUtils() { } /** * Get the AMI ID used to launch the instance. */ public static String getAmiId() { return fetchData(EC2_METADATA_ROOT + "/ami-id"); } /** * Get the index of this instance in the reservation. */ public static String getAmiLaunchIndex() { return fetchData(EC2_METADATA_ROOT + "/ami-launch-index"); } /** * Get the manifest path of the AMI with which the instance was launched. */ public static String getAmiManifestPath() { return fetchData(EC2_METADATA_ROOT + "/ami-manifest-path"); } /** * Get the list of AMI IDs of any instances that were rebundled to created * this AMI. Will only exist if the AMI manifest file contained an * ancestor-amis key. */ public static List<String> getAncestorAmiIds() { return getItems(EC2_METADATA_ROOT + "/ancestor-ami-ids"); } /** * Notifies the instance that it should reboot in preparation for bundling. * Valid values: none | shutdown | bundle-pending. */ public static String getInstanceAction() { return fetchData(EC2_METADATA_ROOT + "/instance-action"); } /** * Get the ID of this instance. */ public static String getInstanceId() { return fetchData(EC2_METADATA_ROOT + "/instance-id"); } /** * Get the type of the instance. */ public static String getInstanceType() { return fetchData(EC2_METADATA_ROOT + "/instance-type"); } /** * Get the local hostname of the instance. In cases where multiple network * interfaces are present, this refers to the eth0 device (the device for * which device-number is 0). */ public static String getLocalHostName() { return fetchData(EC2_METADATA_ROOT + "/local-hostname"); } /** * Get the MAC address of the instance. In cases where multiple network * interfaces are present, this refers to the eth0 device (the device for * which device-number is 0). */ public static String getMacAddress() { return fetchData(EC2_METADATA_ROOT + "/mac"); } /** * Get the private IP address of the instance. In cases where multiple * network interfaces are present, this refers to the eth0 device (the * device for which device-number is 0). */ public static String getPrivateIpAddress() { return fetchData(EC2_METADATA_ROOT + "/local-ipv4"); } /** * Get the Availability Zone in which the instance launched. */ public static String getAvailabilityZone() { return fetchData(EC2_METADATA_ROOT + "/placement/availability-zone"); } /** * Get the list of product codes associated with the instance, if any. */ public static List<String> getProductCodes() { return getItems(EC2_METADATA_ROOT + "/product-codes"); } /** * Get the public key. Only available if supplied at instance launch time. */ public static String getPublicKey() { return fetchData(EC2_METADATA_ROOT + "/public-keys/0/openssh-key"); } /** * Get the ID of the RAM disk specified at launch time, if applicable. */ public static String getRamdiskId() { return fetchData(EC2_METADATA_ROOT + "/ramdisk-id"); } /** * Get the ID of the reservation. */ public static String getReservationId() { return fetchData(EC2_METADATA_ROOT + "/reservation-id"); } /** * Get the list of names of the security groups applied to the instance. */ public static List<String> getSecurityGroups() { return getItems(EC2_METADATA_ROOT + "/security-groups"); } /** * Get the signature of the instance. */ public static String getInstanceSignature() { return fetchData(EC2_DYNAMICDATA_ROOT + INSTANCE_IDENTITY_SIGNATURE); } /** * Returns the current region of this running EC2 instance; or null if * it is unable to do so. The method avoids interpreting other parts of the * instance info JSON document to minimize potential failure. * <p> * The instance info is only guaranteed to be a JSON document per * http://docs * .aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html */ public static String getEC2InstanceRegion() { return doGetEC2InstanceRegion(getData( EC2_DYNAMICDATA_ROOT + INSTANCE_IDENTITY_DOCUMENT)); } static String doGetEC2InstanceRegion(final String json) { if (null != json) { try { return JSON_PARSER.parse(json) .field(REGION) .map(JsonNode::text) .orElseThrow(() -> new IllegalStateException("Region not included in metadata.")); } catch (Exception e) { log.warn("Unable to parse EC2 instance info (" + json + ") : " + e.getMessage(), e); } } return null; } /** * Get the virtual devices associated with the ami, root, ebs, and swap. */ public static Map<String, String> getBlockDeviceMapping() { Map<String, String> blockDeviceMapping = new HashMap<>(); List<String> devices = getItems(EC2_METADATA_ROOT + "/block-device-mapping"); for (String device : devices) { blockDeviceMapping.put(device, getData(EC2_METADATA_ROOT + "/block-device-mapping/" + device)); } return blockDeviceMapping; } /** * Get the list of network interfaces on the instance. */ public static List<NetworkInterface> getNetworkInterfaces() { List<NetworkInterface> networkInterfaces = new LinkedList<>(); List<String> macs = getItems(EC2_METADATA_ROOT + "/network/interfaces/macs/"); for (String mac : macs) { String key = mac.trim(); if (key.endsWith("/")) { key = key.substring(0, key.length() - 1); } networkInterfaces.add(new NetworkInterface(key)); } return networkInterfaces; } /** * Get the metadata sent to the instance */ public static String getUserData() { return getData(EC2_USERDATA_ROOT); } /** * Retrieve some of the data from http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html as a typed * object. This entire class will be removed as part of https://github.com/aws/aws-sdk-java-v2/issues/61, so don't rely on * this sticking around. * * This should not be removed until https://github.com/aws/aws-sdk-java-v2/issues/61 is implemented. */ public static InstanceInfo getInstanceInfo() { return doGetInstanceInfo(getData(EC2_DYNAMICDATA_ROOT + INSTANCE_IDENTITY_DOCUMENT)); } static InstanceInfo doGetInstanceInfo(String json) { if (json != null) { try { Map<String, JsonNode> jsonNode = JSON_PARSER.parse(json).asObject(); return new InstanceInfo(stringValue(jsonNode.get("pendingTime")), stringValue(jsonNode.get("instanceType")), stringValue(jsonNode.get("imageId")), stringValue(jsonNode.get("instanceId")), stringArrayValue(jsonNode.get("billingProducts")), stringValue(jsonNode.get("architecture")), stringValue(jsonNode.get("accountId")), stringValue(jsonNode.get("kernelId")), stringValue(jsonNode.get("ramdiskId")), stringValue(jsonNode.get("region")), stringValue(jsonNode.get("version")), stringValue(jsonNode.get("availabilityZone")), stringValue(jsonNode.get("privateIp")), stringArrayValue(jsonNode.get("devpayProductCodes")), stringArrayValue(jsonNode.get("marketplaceProductCodes"))); } catch (Exception e) { log.warn("Unable to parse dynamic EC2 instance info (" + json + ") : " + e.getMessage(), e); } } return null; } private static String stringValue(JsonNode jsonNode) { if (jsonNode == null || !jsonNode.isString()) { return null; } return jsonNode.asString(); } private static String[] stringArrayValue(JsonNode jsonNode) { if (jsonNode == null || !jsonNode.isArray()) { return null; } return jsonNode.asArray() .stream() .filter(JsonNode::isString) .map(JsonNode::asString) .toArray(String[]::new); } public static String getData(String path) { return getData(path, DEFAULT_QUERY_ATTEMPTS); } public static String getData(String path, int tries) { List<String> items = getItems(path, tries, true); if (null != items && items.size() > 0) { return items.get(0); } return null; } public static List<String> getItems(String path) { return getItems(path, DEFAULT_QUERY_ATTEMPTS, false); } public static List<String> getItems(String path, int tries) { return getItems(path, tries, false); } @SdkTestInternalApi public static void clearCache() { CACHE.clear(); } private static List<String> getItems(String path, int tries, boolean slurp) { if (tries == 0) { throw SdkClientException.builder().message("Unable to contact EC2 metadata service.").build(); } if (SdkSystemSetting.AWS_EC2_METADATA_DISABLED.getBooleanValueOrThrow()) { throw SdkClientException.builder().message("EC2 metadata usage is disabled.").build(); } List<String> items; String token = getToken(); try { String hostAddress = EC2_METADATA_CONFIG_PROVIDER.getEndpoint(); String response = doReadResource(new URI(hostAddress + path), token); if (slurp) { items = Collections.singletonList(response); } else { items = Arrays.asList(response.split("\n")); } return items; } catch (SdkClientException ace) { log.warn("Unable to retrieve the requested metadata."); return null; } catch (IOException | URISyntaxException | RuntimeException e) { // If there is no retry available, just throw exception instead of pausing. if (tries - 1 == 0) { throw SdkClientException.builder().message("Unable to contact EC2 metadata service.").cause(e).build(); } // Retry on any other exceptions int pause = (int) (Math.pow(2, DEFAULT_QUERY_ATTEMPTS - tries) * MINIMUM_RETRY_WAIT_TIME_MILLISECONDS); try { Thread.sleep(pause < MINIMUM_RETRY_WAIT_TIME_MILLISECONDS ? MINIMUM_RETRY_WAIT_TIME_MILLISECONDS : pause); } catch (InterruptedException e1) { Thread.currentThread().interrupt(); } return getItems(path, tries - 1, slurp); } } private static String doReadResource(URI resource, String token) throws IOException { return HttpResourcesUtils.instance().readResource(new DefaultEndpointProvider(resource, token), "GET"); } public static String getToken() { try { return HttpResourcesUtils.instance().readResource(TOKEN_ENDPOINT_PROVIDER, "PUT"); } catch (Exception e) { boolean is400ServiceException = e instanceof SdkServiceException && ((SdkServiceException) e).statusCode() == 400; // metadata resolution must not continue to the token-less flow for a 400 if (is400ServiceException) { throw SdkClientException.builder() .message("Unable to fetch metadata token") .cause(e) .build(); } return null; } } private static String fetchData(String path) { return fetchData(path, false); } private static String fetchData(String path, boolean force) { return fetchData(path, force, DEFAULT_QUERY_ATTEMPTS); } /** * Fetch data using the given path * * @param path the path * @param force whether to force to override the value in the cache * @param attempts the number of attempts that should be executed. * @return the value retrieved from the path */ public static String fetchData(String path, boolean force, int attempts) { if (SdkSystemSetting.AWS_EC2_METADATA_DISABLED.getBooleanValueOrThrow()) { throw SdkClientException.builder().message("EC2 metadata usage is disabled.").build(); } try { if (force || !CACHE.containsKey(path)) { CACHE.put(path, getData(path, attempts)); } return CACHE.get(path); } catch (SdkClientException e) { throw e; } catch (RuntimeException e) { return null; } } /** * All of the metada associated with a network interface on the instance. */ public static class NetworkInterface { private String path; private String mac; private List<String> availableKeys; private Map<String, String> data = new HashMap<>(); public NetworkInterface(String macAddress) { mac = macAddress; path = "/network/interfaces/macs/" + mac + "/"; } /** * The interface's Media Acess Control (mac) address */ public String getMacAddress() { return mac; } /** * The ID of the owner of the network interface.<br> * In multiple-interface environments, an interface can be attached by a * third party, such as Elastic Load Balancing. Traffic on an interface * is always billed to the interface owner. */ public String getOwnerId() { return getData("owner-id"); } /** * The interface's profile. */ public String getProfile() { return getData("profile"); } /** * The interface's local hostname. */ public String getHostname() { return getData("local-hostname"); } /** * The private IP addresses associated with the interface. */ public List<String> getLocalIPv4s() { return getItems("local-ipv4s"); } /** * The interface's public hostname. */ public String getPublicHostname() { return getData("public-hostname"); } /** * The elastic IP addresses associated with the interface.<br> * There may be multiple IP addresses on an instance. */ public List<String> getPublicIPv4s() { return getItems("public-ipv4s"); } /** * Security groups to which the network interface belongs. */ public List<String> getSecurityGroups() { return getItems("security-groups"); } /** * IDs of the security groups to which the network interface belongs. * Returned only for Amazon EC2 instances launched into a VPC. */ public List<String> getSecurityGroupIds() { return getItems("security-group-ids"); } /** * The CIDR block of the Amazon EC2-VPC subnet in which the interface * resides.<br> * Returned only for Amazon EC2 instances launched into a VPC. */ public String getSubnetIPv4CidrBlock() { return getData("subnet-ipv4-cidr-block"); } /** * ID of the subnet in which the interface resides.<br> * Returned only for Amazon EC2 instances launched into a VPC. */ public String getSubnetId() { return getData("subnet-id"); } /** * The CIDR block of the Amazon EC2-VPC in which the interface * resides.<br> * Returned only for Amazon EC2 instances launched into a VPC. */ public String getVpcIPv4CidrBlock() { return getData("vpc-ipv4-cidr-block"); } /** * ID of the Amazon EC2-VPC in which the interface resides.<br> * Returned only for Amazon EC2 instances launched into a VPC. */ public String getVpcId() { return getData("vpc-id"); } /** * Get the private IPv4 address(es) that are associated with the * public-ip address and assigned to that interface. * * @param publicIp * The public IP address * @return Private IPv4 address(es) associated with the public IP * address. */ public List<String> getIPv4Association(String publicIp) { return getItems(EC2_METADATA_ROOT + path + "ipv4-associations/" + publicIp); } private String getData(String key) { if (data.containsKey(key)) { return data.get(key); } // Since the keys are variable, cache a list of which ones are // available // to prevent unnecessary trips to the service. if (null == availableKeys) { availableKeys = EC2MetadataUtils.getItems(EC2_METADATA_ROOT + path); } if (availableKeys.contains(key)) { data.put(key, EC2MetadataUtils.getData(EC2_METADATA_ROOT + path + key)); return data.get(key); } else { return null; } } private List<String> getItems(String key) { if (null == availableKeys) { availableKeys = EC2MetadataUtils.getItems(EC2_METADATA_ROOT + path); } if (availableKeys.contains(key)) { return EC2MetadataUtils .getItems(EC2_METADATA_ROOT + path + key); } else { return Collections.emptyList(); } } } private static final class DefaultEndpointProvider implements ResourcesEndpointProvider { private final URI endpoint; private final String metadataToken; private DefaultEndpointProvider(URI endpoint, String metadataToken) { this.endpoint = endpoint; this.metadataToken = metadataToken; } @Override public URI endpoint() { return endpoint; } @Override public Map<String, String> headers() { Map<String, String> requestHeaders = new HashMap<>(); requestHeaders.put("User-Agent", SdkUserAgent.create().userAgent()); requestHeaders.put("Accept", "*/*"); requestHeaders.put("Connection", "keep-alive"); if (metadataToken != null) { requestHeaders.put(EC2_METADATA_TOKEN_HEADER, metadataToken); } return requestHeaders; } } public static class InstanceInfo { private final String pendingTime; private final String instanceType; private final String imageId; private final String instanceId; private final String[] billingProducts; private final String architecture; private final String accountId; private final String kernelId; private final String ramdiskId; private final String region; private final String version; private final String availabilityZone; private final String privateIp; private final String[] devpayProductCodes; private final String[] marketplaceProductCodes; public InstanceInfo( String pendingTime, String instanceType, String imageId, String instanceId, String[] billingProducts, String architecture, String accountId, String kernelId, String ramdiskId, String region, String version, String availabilityZone, String privateIp, String[] devpayProductCodes, String[] marketplaceProductCodes) { this.pendingTime = pendingTime; this.instanceType = instanceType; this.imageId = imageId; this.instanceId = instanceId; this.billingProducts = billingProducts == null ? null : billingProducts.clone(); this.architecture = architecture; this.accountId = accountId; this.kernelId = kernelId; this.ramdiskId = ramdiskId; this.region = region; this.version = version; this.availabilityZone = availabilityZone; this.privateIp = privateIp; this.devpayProductCodes = devpayProductCodes == null ? null : devpayProductCodes.clone(); this.marketplaceProductCodes = marketplaceProductCodes == null ? null : marketplaceProductCodes.clone(); } public String getPendingTime() { return pendingTime; } public String getInstanceType() { return instanceType; } public String getImageId() { return imageId; } public String getInstanceId() { return instanceId; } public String[] getBillingProducts() { return billingProducts == null ? null : billingProducts.clone(); } public String getArchitecture() { return architecture; } public String getAccountId() { return accountId; } public String getKernelId() { return kernelId; } public String getRamdiskId() { return ramdiskId; } public String getRegion() { return region; } public String getVersion() { return version; } public String getAvailabilityZone() { return availabilityZone; } public String getPrivateIp() { return privateIp; } public String[] getDevpayProductCodes() { return devpayProductCodes == null ? null : devpayProductCodes.clone(); } public String[] getMarketplaceProductCodes() { return marketplaceProductCodes == null ? null : marketplaceProductCodes.clone(); } } }
1,612
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/internal
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/internal/util/ServiceMetadataUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.internal.util; import java.net.URI; import java.util.Map; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.regions.PartitionEndpointKey; import software.amazon.awssdk.regions.PartitionMetadata; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.ServiceEndpointKey; import software.amazon.awssdk.utils.Pair; import software.amazon.awssdk.utils.StringUtils; import software.amazon.awssdk.utils.Validate; @SdkInternalApi public class ServiceMetadataUtils { private static final String[] SEARCH_LIST = {"{service}", "{region}", "{dnsSuffix}" }; private ServiceMetadataUtils() { } public static URI endpointFor(String hostname, String endpointPrefix, String region, String dnsSuffix) { return URI.create(StringUtils.replaceEach(hostname, SEARCH_LIST, new String[] { endpointPrefix, region, dnsSuffix })); } public static Region signingRegion(ServiceEndpointKey key, Map<ServiceEndpointKey, String> signingRegionsByRegion, Map<Pair<String, PartitionEndpointKey>, String> signingRegionsByPartition) { String region = signingRegionsByRegion.get(key); if (region == null) { region = signingRegionsByPartition.get(partitionKey(key)); } return region != null ? Region.of(region) : key.region(); } public static String dnsSuffix(ServiceEndpointKey key, Map<ServiceEndpointKey, String> dnsSuffixesByRegion, Map<Pair<String, PartitionEndpointKey>, String> dnsSuffixesByPartition) { String dnsSuffix = dnsSuffixesByRegion.get(key); if (dnsSuffix == null) { dnsSuffix = dnsSuffixesByPartition.get(partitionKey(key)); } if (dnsSuffix == null) { dnsSuffix = PartitionMetadata.of(key.region()) .dnsSuffix(PartitionEndpointKey.builder().tags(key.tags()).build()); } Validate.notNull(dnsSuffix, "No endpoint known for " + key.tags() + " in " + key.region() + " with this service. " + "A newer SDK version may have an endpoint available, or you could configure the endpoint directly " + "after consulting service documentation."); return dnsSuffix; } public static String hostname(ServiceEndpointKey key, Map<ServiceEndpointKey, String> hostnamesByRegion, Map<Pair<String, PartitionEndpointKey>, String> hostnamesByPartition) { String hostname = hostnamesByRegion.get(key); if (hostname == null) { hostname = hostnamesByPartition.get(partitionKey(key)); } if (hostname == null) { hostname = PartitionMetadata.of(key.region()) .hostname(PartitionEndpointKey.builder().tags(key.tags()).build()); } Validate.notNull(hostname, "No endpoint known for " + key.tags() + " in " + key.region() + " with this service. " + "A newer SDK version may have an endpoint available, or you could configure the endpoint directly " + "after consulting service documentation."); return hostname; } public static Pair<String, PartitionEndpointKey> partitionKey(ServiceEndpointKey key) { return Pair.of(PartitionMetadata.of(key.region()).id(), PartitionEndpointKey.builder().tags(key.tags()).build()); } }
1,613
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/internal
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/internal/util/InstanceProviderTokenEndpointProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.internal.util; import java.net.URI; import java.util.HashMap; import java.util.Map; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.util.SdkUserAgent; import software.amazon.awssdk.regions.util.ResourcesEndpointProvider; @SdkInternalApi public final class InstanceProviderTokenEndpointProvider implements ResourcesEndpointProvider { private static final String TOKEN_RESOURCE_PATH = "/latest/api/token"; private static final String EC2_METADATA_TOKEN_TTL_HEADER = "x-aws-ec2-metadata-token-ttl-seconds"; private static final String DEFAULT_TOKEN_TTL = "21600"; private static final Ec2MetadataConfigProvider EC2_METADATA_CONFIG_PROVIDER = Ec2MetadataConfigProvider.builder() .build(); @Override public URI endpoint() { String host = EC2_METADATA_CONFIG_PROVIDER.getEndpoint(); if (host.endsWith("/")) { host = host.substring(0, host.length() - 1); } return URI.create(host + TOKEN_RESOURCE_PATH); } @Override public Map<String, String> headers() { Map<String, String> requestHeaders = new HashMap<>(); requestHeaders.put("User-Agent", SdkUserAgent.create().userAgent()); requestHeaders.put("Accept", "*/*"); requestHeaders.put("Connection", "keep-alive"); requestHeaders.put(EC2_METADATA_TOKEN_TTL_HEADER, DEFAULT_TOKEN_TTL); return requestHeaders; } }
1,614
0
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk/imds/EndpointModeTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.junit.jupiter.api.Test; /** * Unit Tests to test the EndpointMode enum functionality. */ class EndpointModeTest { @Test void verifyFromValue_when_nullParameterIsPassed(){ assertThat(EndpointMode.fromValue(null)).isEqualTo(null); } @Test void verifyFromValue_when_normalParameterIsPassed(){ assertThat(EndpointMode.fromValue("ipv4")).isEqualTo(EndpointMode.IPV4); } @Test void verifyFromValue_when_wrongParameterIsPassed(){ assertThatThrownBy(() -> { EndpointMode.fromValue("ipv8"); }).hasMessageContaining("Unrecognized value for endpoint mode") .isInstanceOf(IllegalArgumentException.class); } }
1,615
0
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk/imds/Ec2MetadataRetryPolicyTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.retry.backoff.BackoffStrategy; class Ec2MetadataRetryPolicyTest { @Test void equals_hashCode() { BackoffStrategy backoffStrategy = BackoffStrategy.defaultStrategy(); Ec2MetadataRetryPolicy policy = Ec2MetadataRetryPolicy.builder() .numRetries(3) .backoffStrategy(backoffStrategy) .build(); assertThat(policy).isEqualTo(Ec2MetadataRetryPolicy.builder() .numRetries(3) .backoffStrategy(backoffStrategy) .build()); } @Test void builder_setNumRetriesCorrectly() { Ec2MetadataRetryPolicy policy = Ec2MetadataRetryPolicy.builder() .numRetries(3) .build(); assertThat(policy.numRetries()).isEqualTo(3); } }
1,616
0
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk/imds/TestConstants.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds; public class TestConstants { public static final String TOKEN_RESOURCE_PATH = "/latest/api/token"; public static final String TOKEN_HEADER = "x-aws-ec2-metadata-token"; public static final String EC2_METADATA_TOKEN_TTL_HEADER = "x-aws-ec2-metadata-token-ttl-seconds"; public static final String EC2_METADATA_ROOT = "/latest/meta-data"; public static final String AMI_ID_RESOURCE = EC2_METADATA_ROOT + "/ami-id"; }
1,617
0
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk/imds/Ec2MetadataResponseTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.document.Document; import software.amazon.awssdk.thirdparty.jackson.core.JsonParseException; /** * The class tests the utility methods provided by MetadataResponse Class . */ class Ec2MetadataResponseTest { @Test void check_asString_success() { String response = "foobar"; Ec2MetadataResponse metadataResponse = Ec2MetadataResponse.create(response); String result = metadataResponse.asString(); assertThat(result).isEqualTo(response); } @Test void check_asString_failure() { assertThatThrownBy(() -> Ec2MetadataResponse.create(null)).isInstanceOf(NullPointerException.class); } @Test void check_asList_success_with_delimiter() { String response = "sai\ntest"; Ec2MetadataResponse metadataResponse = Ec2MetadataResponse.create(response); List<String> result = metadataResponse.asList(); assertThat(result).hasSize(2); } @Test void check_asList_success_without_delimiter() { String response = "test1-test2"; Ec2MetadataResponse metadataResponse = Ec2MetadataResponse.create(response); List<String> result = metadataResponse.asList(); assertThat(result).hasSize(1); } @Test void check_asDocument_success() { String jsonResponse = "{" + "\"instanceType\":\"m1.small\"," + "\"devpayProductCodes\":[\"bar\",\"foo\"]" + "}"; Ec2MetadataResponse metadataResponse = Ec2MetadataResponse.create(jsonResponse); Document document = metadataResponse.asDocument(); Map<String, Document> expectedMap = new LinkedHashMap<>(); List<Document> documentList = new ArrayList<>(); documentList.add(Document.fromString("bar")); documentList.add(Document.fromString("foo")); expectedMap.put("instanceType", Document.fromString("m1.small")); expectedMap.put("devpayProductCodes", Document.fromList(documentList)); Document expectedDocumentMap = Document.fromMap(expectedMap); assertThat(document).isEqualTo(expectedDocumentMap); } @Test void toDocument_nonJsonFormat_ExpectIllegalArgument() { String malformed = "this is not json"; Ec2MetadataResponse metadataResponse = Ec2MetadataResponse.create(malformed); assertThatThrownBy(metadataResponse::asDocument).getCause().isInstanceOf(JsonParseException.class); } @Test void equals_hasCode() { Ec2MetadataResponse metadataResponse = Ec2MetadataResponse.create("Line 1"); assertThat(metadataResponse).isEqualTo(Ec2MetadataResponse.create("Line 1")) .hasSameHashCodeAs("Line 1"); assertThat(metadataResponse.equals(null)).isFalse(); } }
1,618
0
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk/imds
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk/imds/internal/EndpointProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds.internal; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.params.provider.Arguments.arguments; import static software.amazon.awssdk.imds.EndpointMode.IPV4; import static software.amazon.awssdk.imds.EndpointMode.IPV6; import java.net.URISyntaxException; import java.nio.file.Paths; import java.util.stream.Stream; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.imds.EndpointMode; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileFileSystemSetting; import software.amazon.awssdk.testutils.EnvironmentVariableHelper; import software.amazon.awssdk.utils.internal.SystemSettingUtilsTestBackdoor; /** * Test Class to test the endpoint resolution functionality. */ class EndpointProviderTest { @AfterEach void reset() { System.clearProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE.property()); System.clearProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property()); SystemSettingUtilsTestBackdoor.clearEnvironmentVariableOverrides(); } private static Stream<Arguments> provideEndpointAndEndpointModes() { String testIpv4Url = "http://90:90:90:90"; String testIpv6Url = "http://[9876:ec2::123]"; return Stream.of( arguments(null, true, testIpv4Url, true, "testIPv6", testIpv4Url), arguments(null, true, testIpv6Url, true, "testIPv4", testIpv6Url), arguments(null, true, testIpv4Url, false, "testIPv6", testIpv4Url), arguments(null, true, testIpv6Url, false, "testIPv4", testIpv6Url), arguments(null, false, "unused", true, "testIPv6", "[1234:ec2::456]"), arguments(null, false, "unused", true, "testIPv4", "http://42.42.42.42"), arguments(IPV4, false, "unused", false, "unused", "http://169.254.169.254"), arguments(IPV6, false, "unused", false, "unused", "http://[fd00:ec2::254]") ); } @ParameterizedTest @MethodSource("provideEndpointAndEndpointModes") void validateResolveEndpoint(EndpointMode endpointMode, boolean setEnvVariable, String envEndpoint, boolean setConfigFile, String profile, String expectedValue) throws URISyntaxException { if (setEnvVariable) { System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property(), envEndpoint); } if (setConfigFile) { String testFile = "/profile-config/test-profiles.tst"; SystemSettingUtilsTestBackdoor.addEnvironmentVariableOverride( ProfileFileSystemSetting.AWS_PROFILE.environmentVariable(), profile); SystemSettingUtilsTestBackdoor.addEnvironmentVariableOverride( ProfileFileSystemSetting.AWS_CONFIG_FILE.environmentVariable(), Paths.get(getClass().getResource(testFile).toURI()).toString()); } Ec2MetadataEndpointProvider endpointProvider = Ec2MetadataEndpointProvider.builder().build(); String endpoint = endpointProvider.resolveEndpoint(endpointMode); assertThat(endpoint).isEqualTo(expectedValue); } private static Stream<Arguments> provideEndpointModes() { return Stream.of( arguments(false, "unused", false, "unused", IPV4), arguments(true, "IPv4", true, "IPv4", IPV4), arguments(true, "IPv6", true, "IPv6", IPV6), arguments(true, "IPv6", true, "IPv4", IPV6), arguments(true, "IPv4", true, "IPv6", IPV4), arguments(false, "unused", true, "IPv6", IPV6), arguments(false, "unused", true, "IPv4", IPV4), arguments(true, "IPv6", false, "unused", IPV6), arguments(true, "IPv4", false, "unused", IPV4) ); } @ParameterizedTest @MethodSource("provideEndpointModes") void endpointModeCheck(boolean useEnvVariable, String envVarValue, boolean useConfigFile, String configFileValue, EndpointMode expectedValue) throws URISyntaxException { if (useEnvVariable) { System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE.property(), envVarValue); } if (useConfigFile) { String testFile = "/profile-config/test-profiles.tst"; SystemSettingUtilsTestBackdoor.addEnvironmentVariableOverride( ProfileFileSystemSetting.AWS_PROFILE.environmentVariable(), "test" + configFileValue); SystemSettingUtilsTestBackdoor.addEnvironmentVariableOverride( ProfileFileSystemSetting.AWS_CONFIG_FILE.environmentVariable(), Paths.get(getClass().getResource(testFile).toURI()).toString()); } Ec2MetadataEndpointProvider endpointProvider = Ec2MetadataEndpointProvider.builder().build(); EndpointMode endpointMode = endpointProvider.resolveEndpointMode(); assertThat(endpointMode).isEqualTo(expectedValue); } @Test void endpointFromBuilder_withIpv4_shouldBesetCorrectly() { ProfileFile.Builder content = ProfileFile.builder() .type(ProfileFile.Type.CONFIGURATION) .content(Paths.get("src/test/resources/profile-config/test-profiles.tst")); Ec2MetadataEndpointProvider provider = Ec2MetadataEndpointProvider.builder() .profileFile(content::build) .profileName("testIPv4") .build(); assertThat(provider.resolveEndpointMode()).isEqualTo(IPV4); assertThat(provider.resolveEndpoint(IPV4)).isEqualTo("http://42.42.42.42"); } @Test void endpointFromBuilder_withIpv6_shouldBesetCorrectly() { ProfileFile.Builder content = ProfileFile.builder() .type(ProfileFile.Type.CONFIGURATION) .content(Paths.get("src/test/resources/profile-config/test-profiles.tst")); Ec2MetadataEndpointProvider provider = Ec2MetadataEndpointProvider.builder() .profileFile(content::build) .profileName("testIPv6") .build(); assertThat(provider.resolveEndpointMode()).isEqualTo(IPV6); assertThat(provider.resolveEndpoint(IPV6)).isEqualTo("[1234:ec2::456]"); } }
1,619
0
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk/imds
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk/imds/internal/LargeAsyncRequestTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds.internal; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.exactly; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.put; import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.imds.TestConstants.AMI_ID_RESOURCE; import static software.amazon.awssdk.imds.TestConstants.EC2_METADATA_TOKEN_TTL_HEADER; import static software.amazon.awssdk.imds.TestConstants.TOKEN_HEADER; import static software.amazon.awssdk.imds.TestConstants.TOKEN_RESOURCE_PATH; import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo; import com.github.tomakehurst.wiremock.junit5.WireMockTest; import java.net.URI; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.concurrent.CompletableFuture; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient; import software.amazon.awssdk.imds.Ec2MetadataAsyncClient; import software.amazon.awssdk.imds.Ec2MetadataResponse; @WireMockTest class LargeAsyncRequestTest { private int port; @BeforeEach public void init(WireMockRuntimeInfo wiremock) { this.port = wiremock.getHttpPort(); } @Test void largeRequestTest() throws Exception { int size = 10 * 1024 * 1024; // 10MB byte[] bytes = new byte[size]; for (int i = 0; i < size; i++) { bytes[i] = (byte) (i % 128); } String ec2MetadataContent = new String(bytes, StandardCharsets.US_ASCII); stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn( aResponse().withBody("some-token").withHeader(EC2_METADATA_TOKEN_TTL_HEADER, "21600"))); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withBody(ec2MetadataContent))); try (Ec2MetadataAsyncClient client = Ec2MetadataAsyncClient.builder() .endpoint(URI.create("http://localhost:" + port)) .httpClient(NettyNioAsyncHttpClient.builder().readTimeout(Duration.ofSeconds(30)).build()) .build()) { CompletableFuture<Ec2MetadataResponse> res = client.get(AMI_ID_RESOURCE); Ec2MetadataResponse response = res.get(); assertThat(response.asString()).hasSize(size); assertThat(response.asString()).isEqualTo(ec2MetadataContent); verify(exactly(1), putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)) .withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600"))); verify(exactly(1), getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)) .withHeader(TOKEN_HEADER, equalTo("some-token"))); } } }
1,620
0
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk/imds
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk/imds/internal/Ec2MetadataAsyncClientTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds.internal; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.put; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.AssertionsForClassTypes.catchThrowable; import static org.junit.jupiter.api.Assertions.fail; import static software.amazon.awssdk.imds.TestConstants.AMI_ID_RESOURCE; import static software.amazon.awssdk.imds.TestConstants.EC2_METADATA_TOKEN_TTL_HEADER; import static software.amazon.awssdk.imds.TestConstants.TOKEN_RESOURCE_PATH; import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo; import com.github.tomakehurst.wiremock.junit5.WireMockTest; import java.net.URI; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.internal.http.loader.DefaultSdkAsyncHttpClientBuilder; import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient; import software.amazon.awssdk.imds.Ec2MetadataAsyncClient; import software.amazon.awssdk.imds.Ec2MetadataResponse; @WireMockTest class Ec2MetadataAsyncClientTest extends BaseEc2MetadataClientTest<Ec2MetadataAsyncClient, Ec2MetadataAsyncClient.Builder> { private Ec2MetadataAsyncClient client; private int port; @BeforeEach public void init(WireMockRuntimeInfo wiremock) { this.port = wiremock.getHttpPort(); this.client = Ec2MetadataAsyncClient.builder() .endpoint(URI.create("http://localhost:" + wiremock.getHttpPort())) .build(); } @Override protected int getPort() { return port; } @Override protected BaseEc2MetadataClient overrideClient(Consumer<Ec2MetadataAsyncClient.Builder> builderConsumer) { Ec2MetadataAsyncClient.Builder builder = Ec2MetadataAsyncClient.builder(); builderConsumer.accept(builder); this.client = builder.build(); return (BaseEc2MetadataClient) this.client; } @Override protected void successAssertions(String path, Consumer<Ec2MetadataResponse> assertions) { CompletableFuture<Ec2MetadataResponse> response = client.get(path); try { assertions.accept(response.join()); } catch (Exception e) { fail("unexpected error while exeucting tests", e); } } @Override @SuppressWarnings("unchecked") // safe because of assertion: assertThat(ex).getCause().isInstanceOf(exceptionType); protected <T extends Throwable> void failureAssertions(String path, Class<T> exceptionType, Consumer<T> assertions) { CompletableFuture<Ec2MetadataResponse> future = client.get(path); Throwable ex = catchThrowable(future::join); assertThat(future).isCompletedExceptionally(); assertThat(ex).getCause().isInstanceOf(exceptionType); assertions.accept((T) ex.getCause()); } @Test void get_cancelResponseFuture_shouldCancelHttpRequest() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn( aResponse().withBody("some-token").withFixedDelay(1000))); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn( aResponse().withBody("some-content").withFixedDelay(1000))); CompletableFuture<Ec2MetadataResponse> responseFuture = client.get(AMI_ID_RESOURCE); try { responseFuture.cancel(true); responseFuture.join(); } catch (CancellationException e) { // ignore java.util.concurrent.CancellationException } verify(0, getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE))); } @Test void builder_httpClientWithDefaultBuilder_shouldBuildProperly() { Ec2MetadataAsyncClient buildClient = Ec2MetadataAsyncClient.builder() .httpClient(new DefaultSdkAsyncHttpClientBuilder()) .endpoint(URI.create("http://localhost:" + port)) .build(); stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn( aResponse().withBody("some-token").withHeader(EC2_METADATA_TOKEN_TTL_HEADER, "21600"))); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withBody("some-value"))); CompletableFuture<Ec2MetadataResponse> responseFuture = buildClient.get(AMI_ID_RESOURCE); Ec2MetadataResponse response = responseFuture.join(); assertThat(response.asString()).isEqualTo("some-value"); } @Test void builder_httpClientAndHttpBuilder_shouldThrowException() { assertThatThrownBy(() -> Ec2MetadataAsyncClient.builder() .httpClient(new DefaultSdkAsyncHttpClientBuilder()) .httpClient(NettyNioAsyncHttpClient.create()) .build()) .isInstanceOf(IllegalArgumentException.class); } }
1,621
0
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk/imds
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk/imds/internal/BaseEc2MetadataClientTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds.internal; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.exactly; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.put; import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static com.github.tomakehurst.wiremock.stubbing.Scenario.STARTED; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.params.provider.Arguments.arguments; import static software.amazon.awssdk.imds.EndpointMode.IPV4; import static software.amazon.awssdk.imds.EndpointMode.IPV6; import static software.amazon.awssdk.imds.TestConstants.AMI_ID_RESOURCE; import static software.amazon.awssdk.imds.TestConstants.EC2_METADATA_TOKEN_TTL_HEADER; import static software.amazon.awssdk.imds.TestConstants.TOKEN_HEADER; import static software.amazon.awssdk.imds.TestConstants.TOKEN_RESOURCE_PATH; import com.github.tomakehurst.wiremock.junit5.WireMockTest; import java.net.URI; import java.time.Duration; import java.util.function.Consumer; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.retry.backoff.FixedDelayBackoffStrategy; import software.amazon.awssdk.imds.Ec2MetadataClientBuilder; import software.amazon.awssdk.imds.Ec2MetadataResponse; import software.amazon.awssdk.imds.Ec2MetadataRetryPolicy; import software.amazon.awssdk.imds.EndpointMode; @WireMockTest abstract class BaseEc2MetadataClientTest<T, B extends Ec2MetadataClientBuilder<B, T>> { protected static final int DEFAULT_TOTAL_ATTEMPTS = 4; protected abstract BaseEc2MetadataClient overrideClient(Consumer<B> builderConsumer); protected abstract void successAssertions(String path, Consumer<Ec2MetadataResponse> assertions); protected abstract <T extends Throwable> void failureAssertions(String path, Class<T> exceptionType, Consumer<T> assertions); protected abstract int getPort(); @Test void get_successOnFirstTry_shouldNotRetryAndSucceed() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn( aResponse().withBody("some-token").withHeader(EC2_METADATA_TOKEN_TTL_HEADER, "21600"))); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withBody("{}"))); successAssertions(AMI_ID_RESOURCE, response -> { assertThat(response.asString()).isEqualTo("{}"); verify(exactly(1), putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)) .withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600"))); verify(exactly(1), getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)) .withHeader(TOKEN_HEADER, equalTo("some-token"))); }); } @Test void get_failsEverytime_shouldRetryAndFails() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn( aResponse().withBody("some-token").withHeader(EC2_METADATA_TOKEN_TTL_HEADER, "21600"))); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withStatus(500).withBody("Error 500"))); failureAssertions(AMI_ID_RESOURCE, SdkClientException.class, ex -> { verify(exactly(1), putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)) .withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600"))); verify(exactly(DEFAULT_TOTAL_ATTEMPTS), getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)) .withHeader(TOKEN_HEADER, equalTo("some-token"))); }); } @Test void get_returnsStatus4XX_shouldFailsAndNotRetry() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn( aResponse().withBody("some-token").withHeader(EC2_METADATA_TOKEN_TTL_HEADER, "21600"))); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withStatus(400).withBody("error"))); failureAssertions(AMI_ID_RESOURCE, SdkClientException.class, ex -> { verify(exactly(1), putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)) .withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600"))); verify(exactly(1), getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)) .withHeader(TOKEN_HEADER, equalTo("some-token"))); }); } @Test void get_failsOnceThenSucceed_withCustomClient_shouldSucceed() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn( aResponse().withBody("some-token").withHeader(EC2_METADATA_TOKEN_TTL_HEADER, "21600"))); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)) .inScenario("Retry Scenario") .whenScenarioStateIs(STARTED) .willReturn(aResponse().withStatus(500).withBody("Error 500")) .willSetStateTo("Cause Success")); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)) .inScenario("Retry Scenario") .whenScenarioStateIs("Cause Success") .willReturn(aResponse().withBody("{}"))); overrideClient(builder -> builder .retryPolicy(Ec2MetadataRetryPolicy.builder() .numRetries(5) .backoffStrategy(FixedDelayBackoffStrategy.create(Duration.ofMillis(300))) .build()) .endpoint(URI.create("http://localhost:" + getPort())) .tokenTtl(Duration.ofSeconds(1024))); successAssertions(AMI_ID_RESOURCE, response -> { assertThat(response.asString()).isEqualTo("{}"); verify(exactly(1), putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)) .withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("1024"))); verify(exactly(2), getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)) .withHeader(TOKEN_HEADER, equalTo("some-token"))); }); } @Test void getToken_failsEverytime_shouldRetryAndFailsAndNotCallService() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withStatus(500).withBody("Error 500"))); failureAssertions(AMI_ID_RESOURCE, SdkClientException.class, ex -> { verify(exactly(DEFAULT_TOTAL_ATTEMPTS), putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)) .withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600"))); verify(exactly(0), getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)) .withHeader(TOKEN_HEADER, equalTo("some-token"))); }); } @Test void getToken_returnsStatus4XX_shouldFailsAndNotRetry() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withStatus(400).withBody("ERROR 400"))); failureAssertions(AMI_ID_RESOURCE, SdkClientException.class, ex -> { verify(exactly(1), putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)) .withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600"))); verify(exactly(0), getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)) .withHeader(TOKEN_HEADER, equalTo("some-token"))); }); } @Test void getToken_failsOnceThenSucceed_withCustomClient_shouldSucceed() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).inScenario("Retry Scenario") .whenScenarioStateIs(STARTED) .willReturn(aResponse().withStatus(500).withBody("Error 500")) .willSetStateTo("Cause Success")); stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).inScenario("Retry Scenario") .whenScenarioStateIs("Cause Success") .willReturn( aResponse() .withBody("some-token") .withHeader(EC2_METADATA_TOKEN_TTL_HEADER, "21600"))); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).inScenario("Retry Scenario") .whenScenarioStateIs("Cause Success") .willReturn(aResponse().withBody("Success"))); overrideClient(builder -> builder .retryPolicy(Ec2MetadataRetryPolicy.builder() .numRetries(5) .backoffStrategy(FixedDelayBackoffStrategy.create(Duration.ofMillis(300))) .build()) .endpoint(URI.create("http://localhost:" + getPort())) .build()); successAssertions(AMI_ID_RESOURCE, response -> { assertThat(response.asString()).isEqualTo("Success"); verify(exactly(2), putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)) .withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600"))); verify(exactly(1), getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)) .withHeader(TOKEN_HEADER, equalTo("some-token"))); }); } @Test void get_noRetries_shouldNotRetry() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withBody("some-token"))); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withStatus(500).withBody("Error 500"))); overrideClient(builder -> builder .endpoint(URI.create("http://localhost:" + getPort())) .retryPolicy(Ec2MetadataRetryPolicy.none()).build()); failureAssertions(AMI_ID_RESOURCE, SdkClientException.class, ex -> { verify(1, putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)) .withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600"))); verify(1, putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)) .withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600"))); }); } @Test void builder_endpointAndEndpointModeSpecified_shouldThrowIllegalArgException() { assertThatThrownBy(() -> overrideClient(builder -> builder .endpoint(URI.create("http://localhost:" + getPort())) .endpointMode(IPV6))) .isInstanceOf(IllegalArgumentException.class); } @Test void builder_defaultValue_clientShouldUseIPV4Endpoint() { BaseEc2MetadataClient client = overrideClient(builder -> { }); assertThat(client.endpoint).hasToString("http://169.254.169.254"); } @Test void builder_setEndpoint_shouldUseEndpoint() { BaseEc2MetadataClient client = overrideClient(builder -> builder.endpoint(URI.create("http://localhost:" + 12312))); assertThat(client.endpoint).hasToString("http://localhost:" + 12312); } @ParameterizedTest @MethodSource("endpointArgumentSource") void builder_setEndPointMode_shouldUseEndpointModeValue(EndpointMode endpointMode, String value) { BaseEc2MetadataClient client = overrideClient(builder -> builder.endpointMode(endpointMode)); assertThat(client.endpoint).hasToString(value); } private static Stream<Arguments> endpointArgumentSource() { return Stream.of( arguments(IPV4, "http://169.254.169.254"), arguments(IPV6, "http://[fd00:ec2::254]")); } @Test void get_tokenExpiresWhileRetrying_shouldSucceedWithNewToken() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn( aResponse().withBody("some-token").withHeader(EC2_METADATA_TOKEN_TTL_HEADER, "2"))); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).inScenario("Retry Scenario") .whenScenarioStateIs(STARTED) .willReturn(aResponse().withStatus(500) .withBody("Error 500") .withFixedDelay(700)) .willSetStateTo("Retry-1")); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).inScenario("Retry Scenario") .whenScenarioStateIs("Retry-1") .willReturn(aResponse().withStatus(500) .withBody("Error 500") .withFixedDelay(700)) .willSetStateTo("Retry-2")); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).inScenario("Retry Scenario") .whenScenarioStateIs("Retry-2") .willReturn(aResponse().withStatus(500) .withBody("Error 500") .withFixedDelay(700)) .willSetStateTo("Retry-3")); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).inScenario("Retry Scenario") .whenScenarioStateIs("Retry-3") .willReturn(aResponse().withStatus(200) .withBody("Success") .withFixedDelay(700))); overrideClient(builder -> builder .tokenTtl(Duration.ofSeconds(2)) .endpoint(URI.create("http://localhost:" + getPort())) .build()); successAssertions(AMI_ID_RESOURCE, response -> { assertThat(response.asString()).isEqualTo("Success"); verify(exactly(2), putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)) .withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("2"))); verify(exactly(4), getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)) .withHeader(TOKEN_HEADER, equalTo("some-token"))); }); } @Test void getToken_responseWithoutTtlHeaders_shouldFailAndNotRetry() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn( aResponse().withBody("some-token"))); // no EC2_METADATA_TOKEN_TTL_HEADER header stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withStatus(200).withBody("some-value"))); failureAssertions(AMI_ID_RESOURCE, SdkClientException.class, e -> { verify(exactly(1), putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)) .withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600"))); verify(exactly(0), getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)) .withHeader(TOKEN_HEADER, equalTo("some-token"))); }); } @Test void getToken_responseTtlHeadersNotANumber_shouldFailAndNotRetry() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withBody("some-token"))); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withStatus(200).withBody("some-value"))); stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn( aResponse().withBody("some-token").withHeader(EC2_METADATA_TOKEN_TTL_HEADER, "not-a-number"))); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withStatus(200).withBody("some-value"))); failureAssertions(AMI_ID_RESOURCE, SdkClientException.class, e -> { verify(exactly(1), putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)) .withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600"))); verify(exactly(0), getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)) .withHeader(TOKEN_HEADER, equalTo("some-token"))); }); } }
1,622
0
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk/imds
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk/imds/internal/MultipleAsyncRequestsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds.internal; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.exactly; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.put; import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.imds.TestConstants.AMI_ID_RESOURCE; import static software.amazon.awssdk.imds.TestConstants.EC2_METADATA_TOKEN_TTL_HEADER; import static software.amazon.awssdk.imds.TestConstants.TOKEN_HEADER; import static software.amazon.awssdk.imds.TestConstants.TOKEN_RESOURCE_PATH; import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder; import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo; import com.github.tomakehurst.wiremock.junit5.WireMockTest; import java.net.URI; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.imds.Ec2MetadataAsyncClient; import software.amazon.awssdk.imds.Ec2MetadataResponse; @WireMockTest class MultipleAsyncRequestsTest { private int port; @BeforeEach public void init(WireMockRuntimeInfo wiremock) { this.port = wiremock.getHttpPort(); } @Test void multipleRequests() { int totalRequests = 128; String tokenValue = "some-token"; stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn( aResponse().withBody(tokenValue).withHeader(EC2_METADATA_TOKEN_TTL_HEADER, "21600"))); for (int i = 0; i < totalRequests; i++) { ResponseDefinitionBuilder responseStub = aResponse().withStatus(200).withBody("response::" + i); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE + "/" + i)).willReturn(responseStub)); } Ec2MetadataAsyncClient client = Ec2MetadataAsyncClient.builder() .endpoint(URI.create("http://localhost:" + this.port)) .build(); List<CompletableFuture<Ec2MetadataResponse>> requests = Stream.iterate(0, x -> x + 1) .map(i -> client.get(AMI_ID_RESOURCE + "/" + i)) .limit(totalRequests) .collect(Collectors.toList()); CompletableFuture<List<Ec2MetadataResponse>> responses = CompletableFuture .allOf(requests.toArray(new CompletableFuture[0])) .thenApply(unusedVoid -> requests.stream() .map(CompletableFuture::join) .collect(Collectors.toList())); List<Ec2MetadataResponse> resolvedResponses = responses.join(); for (int i = 0; i < totalRequests; i++) { Ec2MetadataResponse response = resolvedResponses.get(i); assertThat(response.asString()).isEqualTo("response::" + i); } verify(exactly(1), putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)) .withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600"))); verify(exactly(totalRequests), getRequestedFor(urlPathMatching(AMI_ID_RESOURCE + "/" + "\\d+")) .withHeader(TOKEN_HEADER, equalTo(tokenValue))); } }
1,623
0
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk/imds
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk/imds/internal/Ec2MetadataClientTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds.internal; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.put; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.AssertionsForClassTypes.catchThrowable; import static software.amazon.awssdk.imds.TestConstants.AMI_ID_RESOURCE; import static software.amazon.awssdk.imds.TestConstants.EC2_METADATA_TOKEN_TTL_HEADER; import static software.amazon.awssdk.imds.TestConstants.TOKEN_RESOURCE_PATH; import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo; import com.github.tomakehurst.wiremock.junit5.WireMockTest; import java.net.URI; import java.util.function.Consumer; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.internal.http.loader.DefaultSdkHttpClientBuilder; import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient; import software.amazon.awssdk.imds.Ec2MetadataClient; import software.amazon.awssdk.imds.Ec2MetadataResponse; @WireMockTest class Ec2MetadataClientTest extends BaseEc2MetadataClientTest<Ec2MetadataClient, Ec2MetadataClient.Builder> { private Ec2MetadataClient client; private int port; @BeforeEach public void init(WireMockRuntimeInfo wiremock) { this.port = wiremock.getHttpPort(); this.client = Ec2MetadataClient.builder() .endpoint(URI.create("http://localhost:" + wiremock.getHttpPort())) .build(); } @Override protected int getPort() { return port; } @Override protected BaseEc2MetadataClient overrideClient(Consumer<Ec2MetadataClient.Builder> builderConsumer) { Ec2MetadataClient.Builder builder = Ec2MetadataClient.builder(); builderConsumer.accept(builder); this.client = builder.build(); return (BaseEc2MetadataClient) this.client; } @Override protected void successAssertions(String path, Consumer<Ec2MetadataResponse> assertions) { Ec2MetadataResponse response = client.get(path); assertions.accept(response); } @Override @SuppressWarnings("unchecked") // safe because of assertion: assertThat(ex).isInstanceOf(exceptionType); protected <T extends Throwable> void failureAssertions(String path, Class<T> exceptionType, Consumer<T> assertions) { Throwable ex = catchThrowable(() -> client.get(path)); assertThat(ex).isInstanceOf(exceptionType); assertions.accept((T) ex); } @Test void builder_httpClientWithDefaultBuilder_shouldBuildProperly() { Ec2MetadataClient buildClient = Ec2MetadataClient.builder() .httpClient(new DefaultSdkHttpClientBuilder()) .endpoint(URI.create("http://localhost:" + port)) .build(); stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn( aResponse().withBody("some-token").withHeader(EC2_METADATA_TOKEN_TTL_HEADER, "21600"))); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withBody("{}"))); Ec2MetadataResponse response = buildClient.get(AMI_ID_RESOURCE); assertThat(response.asString()).isEqualTo("{}"); } @Test void builder_httpClientAndHttpBuilder_shouldThrowException() { assertThatThrownBy(() -> Ec2MetadataClient.builder() .httpClient(new DefaultSdkHttpClientBuilder()) .httpClient(UrlConnectionHttpClient.create()) .build()) .isInstanceOf(IllegalArgumentException.class); } }
1,624
0
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk/imds
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk/imds/internal/CachedTokenClientTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds.internal; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.exactly; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.put; import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static com.github.tomakehurst.wiremock.stubbing.Scenario.STARTED; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static software.amazon.awssdk.imds.TestConstants.EC2_METADATA_TOKEN_TTL_HEADER; import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo; import com.github.tomakehurst.wiremock.junit5.WireMockTest; import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.URI; import java.nio.charset.StandardCharsets; import java.time.Duration; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.http.AbortableInputStream; import software.amazon.awssdk.http.ExecutableHttpRequest; import software.amazon.awssdk.http.HttpExecuteRequest; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.imds.Ec2MetadataClient; import software.amazon.awssdk.imds.Ec2MetadataResponse; @WireMockTest class CachedTokenClientTest { private Ec2MetadataClient.Builder clientBuilder; @BeforeEach void init(WireMockRuntimeInfo wmRuntimeInfo) { this.clientBuilder = Ec2MetadataClient.builder() .endpoint(URI.create("http://localhost:" + wmRuntimeInfo.getHttpPort())); } @AfterEach void tearDown(WireMockRuntimeInfo wmRuntimeInfo) { wmRuntimeInfo.getWireMock().resetMappings(); } @Test void get_tokenFailsError4xx_shouldNotRetry() throws IOException { SdkHttpClient mockClient = mock(SdkHttpClient.class); ExecutableHttpRequest mockRequest = mock(ExecutableHttpRequest.class); when(mockClient.prepareRequest(any(HttpExecuteRequest.class))).thenReturn(mockRequest); AbortableInputStream content = AbortableInputStream.create(new ByteArrayInputStream("ERROR 400".getBytes(StandardCharsets.UTF_8))); SdkHttpResponse httpResponse = SdkHttpFullResponse.builder() .statusCode(400) .build(); HttpExecuteResponse executeResponse = HttpExecuteResponse.builder() .response(httpResponse) .responseBody(content) .build(); when(mockRequest.call()).thenReturn(executeResponse); Ec2MetadataClient imdsClient = Ec2MetadataClient.builder().httpClient(mockClient).build(); assertThatThrownBy(() ->imdsClient.get("/latest/meta-data/ami-id")).isInstanceOf(SdkClientException.class); ArgumentCaptor<HttpExecuteRequest> requestCaptor = ArgumentCaptor.forClass(HttpExecuteRequest.class); Mockito.verify(mockClient).prepareRequest(requestCaptor.capture()); SdkHttpRequest httpRequest = requestCaptor.getValue().httpRequest(); assertThat(httpRequest.encodedPath()).isEqualTo("/latest/api/token"); assertThat(httpRequest.firstMatchingHeader("x-aws-ec2-metadata-token-ttl-seconds").get()).isEqualTo("21600"); } @Test void getToken_failsError5xx_shouldRetryUntilMaxRetriesIsReached() { stubFor(put(urlPathEqualTo("/latest/api/token")).willReturn(aResponse().withStatus(500).withBody("ERROR 500"))); stubFor(get(urlPathEqualTo("/latest/meta-data/ami-id")).willReturn(aResponse().withBody("{}"))); assertThatThrownBy(() -> clientBuilder.build().get("/latest/meta-data/ami-id")).isInstanceOf(SdkClientException.class); verify(exactly(4), putRequestedFor(urlPathEqualTo("/latest/api/token")) .withHeader("x-aws-ec2-metadata-token-ttl-seconds", equalTo("21600"))); } @Test void getToken_failsThenSucceeds_doesCacheTokenThatSucceeds() { stubFor(put(urlPathEqualTo("/latest/api/token")).inScenario("Retry Scenario") .whenScenarioStateIs(STARTED) .willReturn(aResponse().withStatus(500).withBody("Error 500")) .willSetStateTo("Cause Success")); stubFor(put(urlPathEqualTo("/latest/api/token")).inScenario("Retry Scenario") .whenScenarioStateIs("Cause Success") .willReturn(aResponse() .withBody("token-ok") .withHeader(EC2_METADATA_TOKEN_TTL_HEADER, "21600"))); stubFor(get(urlPathEqualTo("/latest/meta-data/ami-id")).inScenario("Retry Scenario") .whenScenarioStateIs("Cause Success") .willReturn(aResponse().withBody("Success"))); // 3 requests Ec2MetadataClient client = clientBuilder.build(); Ec2MetadataResponse response = client.get("/latest/meta-data/ami-id"); assertThat(response.asString()).isEqualTo("Success"); response = client.get("/latest/meta-data/ami-id"); assertThat(response.asString()).isEqualTo("Success"); response = client.get("/latest/meta-data/ami-id"); assertThat(response.asString()).isEqualTo("Success"); verify(exactly(2), putRequestedFor(urlPathEqualTo("/latest/api/token")) .withHeader("x-aws-ec2-metadata-token-ttl-seconds", equalTo("21600"))); verify(exactly(3), getRequestedFor(urlPathEqualTo("/latest/meta-data/ami-id")) .withHeader("x-aws-ec2-metadata-token", equalTo("token-ok"))); } @Test void get_multipleCallsSuccess_shouldReuseToken() throws Exception { stubFor(put(urlPathEqualTo("/latest/api/token")).willReturn( aResponse().withBody("some-token").withHeader(EC2_METADATA_TOKEN_TTL_HEADER, "21600"))); stubFor(get(urlPathEqualTo("/latest/meta-data/ami-id")) .willReturn(aResponse().withBody("{}").withFixedDelay(800))); int tokenTTlSeconds = 4; Ec2MetadataClient client = clientBuilder.tokenTtl(Duration.ofSeconds(tokenTTlSeconds)).build(); int totalRequests = 10; for (int i = 0; i < totalRequests; i++) { Ec2MetadataResponse response = client.get("/latest/meta-data/ami-id"); assertThat(response.asString()).isEqualTo("{}"); } verify(exactly(2), putRequestedFor(urlPathEqualTo("/latest/api/token")) .withHeader("x-aws-ec2-metadata-token-ttl-seconds", equalTo(String.valueOf(tokenTTlSeconds)))); verify(exactly(totalRequests), getRequestedFor(urlPathEqualTo("/latest/meta-data/ami-id")) .withHeader("x-aws-ec2-metadata-token", equalTo("some-token"))); } }
1,625
0
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk/imds/internal/unmarshall
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk/imds/internal/unmarshall/document/DocumentUnmarshallerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds.internal.unmarshall.document; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import java.math.BigDecimal; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.SdkNumber; import software.amazon.awssdk.core.document.Document; import software.amazon.awssdk.protocols.jsoncore.JsonNode; import software.amazon.awssdk.protocols.jsoncore.internal.EmbeddedObjectJsonNode; class DocumentUnmarshallerTest { @Test void testDocumentFromNumberNode() { JsonNode node = JsonNode.parser().parse("100"); assertThat(Document.fromNumber(SdkNumber.fromInteger(100)).asNumber().intValue()) .isEqualTo(node.visit(new DocumentUnmarshaller()).asNumber().intValue()); } @Test void testDocumentFromBoolean() { JsonNode node = JsonNode.parser().parse("true"); assertThat(Document.fromBoolean(true)).isEqualTo(node.visit(new DocumentUnmarshaller())); } @Test void testDocumentFromString() { JsonNode node = JsonNode.parser().parse("\"100.00\""); assertThat(Document.fromString("100.00")).isEqualTo(node.visit(new DocumentUnmarshaller())); } @Test void testDocumentFromNull() { JsonNode node = JsonNode.parser().parse("null"); assertThat(Document.fromNull()).isEqualTo(node.visit(new DocumentUnmarshaller())); } @Test void testExceptionIsThrownFromEmbededObjectType() { assertThatExceptionOfType(UnsupportedOperationException.class) .isThrownBy(() -> new EmbeddedObjectJsonNode(new Object()).visit(new DocumentUnmarshaller())); } @Test void testDocumentFromObjectNode(){ JsonNode node = JsonNode.parser().parse("{\"firstKey\": \"firstValue\", \"secondKey\": \"secondValue\"}"); Document documentMap = node.visit(new DocumentUnmarshaller()); Map<String, Document> expectedMap = new LinkedHashMap<>(); expectedMap.put("firstKey", Document.fromString("firstValue")); expectedMap.put("secondKey", Document.fromString("secondValue")); Document expectedDocumentMap = Document.fromMap(expectedMap); assertThat(documentMap).isEqualTo(expectedDocumentMap); } @Test void testDocumentFromArrayNode(){ JsonNode node = JsonNode.parser().parse("[\"One\", 10, true, null]"); List<Document> documentList = new ArrayList<>(); documentList.add(Document.fromString("One")); documentList.add(Document.fromNumber(SdkNumber.fromBigDecimal(BigDecimal.TEN))); documentList.add(Document.fromBoolean(true)); documentList.add(Document.fromNull()); Document document = Document.fromList(documentList); Document actualDocument = node.visit(new DocumentUnmarshaller()); assertThat(actualDocument).isEqualTo(document); } }
1,626
0
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds/Ec2MetadataRetryPolicy.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds; import java.util.Objects; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.retry.RetryMode; import software.amazon.awssdk.core.retry.backoff.BackoffStrategy; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * Interface for specifying a retry policy to use when evaluating whether or not a request should be retried, and the gap * between each retry. The {@link #builder()} can be used to construct a retry policy with numRetries and backoffStrategy. * <p> * When using the {@link #builder()} the SDK will use default values for fields that are not provided.A custom BackoffStrategy * can be used to construct a policy or a default {@link BackoffStrategy} is used. * * @see BackoffStrategy for a list of SDK provided backoff strategies */ @SdkPublicApi public final class Ec2MetadataRetryPolicy implements ToCopyableBuilder<Ec2MetadataRetryPolicy.Builder, Ec2MetadataRetryPolicy> { private static final int DEFAULT_RETRY_ATTEMPTS = 3; private final BackoffStrategy backoffStrategy; private final Integer numRetries; private Ec2MetadataRetryPolicy(BuilderImpl builder) { this.numRetries = Validate.getOrDefault(builder.numRetries, () -> DEFAULT_RETRY_ATTEMPTS); this.backoffStrategy = Validate.getOrDefault(builder.backoffStrategy, () -> BackoffStrategy.defaultStrategy(RetryMode.STANDARD)); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } Ec2MetadataRetryPolicy ec2MetadataRetryPolicy = (Ec2MetadataRetryPolicy) obj; if (!Objects.equals(numRetries, ec2MetadataRetryPolicy.numRetries)) { return false; } return Objects.equals(backoffStrategy, ec2MetadataRetryPolicy.backoffStrategy); } @Override public int hashCode() { int result = Math.max(numRetries, 0); result = 31 * result + (backoffStrategy != null ? backoffStrategy.hashCode() : 0); return result; } @Override public String toString() { return "Ec2MetadataRetryPolicy{" + "backoffStrategy=" + backoffStrategy.toString() + ", numRetries=" + numRetries + '}'; } /** * Method to return the number of retries allowed. * @return The number of retries allowed. */ public int numRetries() { return numRetries; } /** * Method to return the BackoffStrategy used. * @return The backoff Strategy used. */ public BackoffStrategy backoffStrategy() { return backoffStrategy; } public static Builder builder() { return new BuilderImpl(); } @Override public Builder toBuilder() { return builder().numRetries(numRetries) .backoffStrategy(backoffStrategy); } public static Ec2MetadataRetryPolicy none() { return builder().numRetries(0).build(); } public interface Builder extends CopyableBuilder<Ec2MetadataRetryPolicy.Builder, Ec2MetadataRetryPolicy> { /** * Configure the backoff strategy that should be used for waiting in between retry attempts. */ Builder backoffStrategy(BackoffStrategy backoffStrategy); /** * Configure the maximum number of times that a single request should be retried, assuming it fails for a retryable error. */ Builder numRetries(Integer numRetries); } private static final class BuilderImpl implements Builder { private Integer numRetries; private BackoffStrategy backoffStrategy; private BuilderImpl() { } @Override public Builder numRetries(Integer numRetries) { this.numRetries = numRetries; return this; } @Override public Builder backoffStrategy(BackoffStrategy backoffStrategy) { this.backoffStrategy = backoffStrategy; return this; } @Override public Ec2MetadataRetryPolicy build() { return new Ec2MetadataRetryPolicy(this); } } }
1,627
0
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds/EndpointMode.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds; import software.amazon.awssdk.annotations.SdkPublicApi; /** * Enum Class for the Endpoint Mode. */ @SdkPublicApi public enum EndpointMode { IPV4, IPV6; /** * Returns the appropriate EndpointMode Value after parsing the parameter. * @param s EndpointMode in String Format. * @return EndpointMode enumValue (IPV4 or IPV6). * @throws IllegalArgumentException Unrecognized value for endpoint mode. */ public static EndpointMode fromValue(String s) { if (s == null) { return null; } for (EndpointMode value : values()) { if (value.name().equalsIgnoreCase(s)) { return value; } } throw new IllegalArgumentException("Unrecognized value for endpoint mode: " + s); } }
1,628
0
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds/Ec2MetadataResponse.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds; import java.io.UncheckedIOException; import java.util.Arrays; import java.util.List; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.document.Document; import software.amazon.awssdk.imds.internal.unmarshall.document.DocumentUnmarshaller; import software.amazon.awssdk.protocols.jsoncore.JsonNode; import software.amazon.awssdk.protocols.jsoncore.JsonNodeParser; import software.amazon.awssdk.thirdparty.jackson.core.JsonParseException; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.Validate; /** * This class is used for response handling and parsing the metadata fetched by the get call in the {@link Ec2MetadataClient} * interface. It provides convenience methods to the users to parse the metadata as a String and List. Also provides * ways to parse the metadata as Document type if it is in the json format. */ @SdkPublicApi public final class Ec2MetadataResponse { private static final JsonNodeParser JSON_NODE_PARSER = JsonNode.parserBuilder().removeErrorLocations(true).build(); private final String body; private Ec2MetadataResponse(String body) { this.body = Validate.notNull(body, "Metadata is null"); } /** * Create a {@link Ec2MetadataResponse} with the given body as its content. * @param body the content of the response * @return a {@link Ec2MetadataResponse} with the given body as its content. */ public static Ec2MetadataResponse create(String body) { return new Ec2MetadataResponse(body); } /** * @return String Representation of the Metadata Response Body. */ public String asString() { return body; } /** * Splits the Metadata response body on new line character and returns it as a list. * @return The Metadata response split on each line. */ public List<String> asList() { return Arrays.asList(body.split("\n")); } /** * Parses the response String into a {@link Document} type. This method can be used for * parsing the metadata in a String Json Format. * @return Document Representation, as json, of the Metadata Response Body. * @throws UncheckedIOException (wrapping a {@link JsonParseException} if the Response body is not of JSON format. */ public Document asDocument() { JsonNode node = JSON_NODE_PARSER.parse(body); return node.visit(new DocumentUnmarshaller()); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Ec2MetadataResponse that = (Ec2MetadataResponse) o; return body.equals(that.body); } @Override public int hashCode() { return body.hashCode(); } @Override public String toString() { return ToString.builder("MetadataResponse") .add("body", body) .build(); } }
1,629
0
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds/Ec2MetadataClient.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.imds.internal.DefaultEc2MetadataClient; import software.amazon.awssdk.utils.SdkAutoCloseable; /** * Interface to represent the Ec2Metadata Client Class. Used to access instance metadata from a running EC2 instance. * <h2>Instantiate the Ec2MetadataClient</h2> * <h3>Default configuration</h3> * {@snippet : * Ec2MetadataClient client = Ec2MetadataClient.create(); * } * <h3>Custom configuration</h3> * Example of a client configured for using IPV6 and a fixed delay for retry attempts : * {@snippet : * Ec2MetadataClient client = Ec2MetadataClient.builder() * .retryPolicy(p -> p.backoffStrategy(FixedDelayBackoffStrategy.create(Duration.ofMillis(500)))) * .endpointMode(EndpointMode.IPV6) * .build(); * } * <h2>Use the client</h2> * To retrieve EC2 Instance Metadata, call the {@code get} method on the client with a path to an instance metadata: * {@snippet : * Ec2MetadataClient client = Ec2MetadataClient.create(); * Ec2MetadataResponse response = client.get("/latest/meta-data/"); * System.out.println(response.asString()); * } * <h2>Closing the client</h2> * Once all operations are done, you may close the client to free any resources used by it. * {@snippet : * Ec2MetadataClient client = Ec2MetadataClient.create(); * // ... do the things * client.close(); * } * <br/>Note: A single client instance should be reused for multiple requests when possible. */ @SdkPublicApi public interface Ec2MetadataClient extends SdkAutoCloseable { /** * Gets the specified instance metadata value by the given path. For more information about instance metadata, check the * <a href=https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html>Instance metadata documentation</a> * * @param path Input path * @return Instance metadata value as part of MetadataResponse Object */ Ec2MetadataResponse get(String path); /** * Create an {@link Ec2MetadataClient} instance using the default values. * * @return the client instance. */ static Ec2MetadataClient create() { return builder().build(); } /** * Creates a default builder for {@link Ec2MetadataClient}. */ static Builder builder() { return DefaultEc2MetadataClient.builder(); } /** * The builder definition for a {@link Ec2MetadataClient}. */ interface Builder extends Ec2MetadataClientBuilder<Ec2MetadataClient.Builder, Ec2MetadataClient> { /** * Define the http client used by the Ec2 Metadata client. If provided, the Ec2MetadataClient will <em>NOT</em> manage the * lifetime if the httpClient and must therefore be closed explicitly by calling the {@link SdkHttpClient#close()} * method on it. * <p> * If not specified, the IMDS client will look for a SdkHttpClient class included in the classpath of the * application and create a new instance of that class, managed by the IMDS Client, that will be closed when the IMDS * Client is closed. If no such class can be found, will throw a {@link SdkClientException}. * * @param httpClient the http client * @return a reference to this builder */ Builder httpClient(SdkHttpClient httpClient); /** * A http client builder used to retrieve an instance of an {@link SdkHttpClient}. If specified, the Ec2 Metadata Client * will use the instance returned by the builder and manage its lifetime by closing the http client once the Ec2 Client * itself is closed. * * @param builder the builder to used to retrieve an instance. * @return a reference to this builder */ Builder httpClient(SdkHttpClient.Builder<?> builder); } }
1,630
0
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds/Ec2MetadataClientBuilder.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds; import java.net.URI; import java.time.Duration; import java.util.function.Consumer; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.retry.RetryMode; import software.amazon.awssdk.core.retry.backoff.BackoffStrategy; import software.amazon.awssdk.imds.internal.Ec2MetadataEndpointProvider; import software.amazon.awssdk.utils.builder.SdkBuilder; /** * Base shared builder interface for Ec2MetadataClients, sync and async. * @param <B> the Builder Type * @param <T> the Ec2MetadataClient Type */ @SdkPublicApi public interface Ec2MetadataClientBuilder<B, T> extends SdkBuilder<Ec2MetadataClientBuilder<B, T>, T> { /** * Define the retry policy which includes the number of retry attempts for any failed request. * <p> * If not specified, defaults to 3 retry attempts and a {@link BackoffStrategy#defaultStrategy()} backoff strategy} that * uses {@link RetryMode#STANDARD}. Can be also specified by using the * {@link Ec2MetadataClientBuilder#retryPolicy(Consumer)} method. if any of the retryPolicy methods are called multiple times, * only the last invocation will be considered. * * @param retryPolicy The retry policy which includes the number of retry attempts for any failed request. * @return a reference to this builder */ B retryPolicy(Ec2MetadataRetryPolicy retryPolicy); /** * Define the retry policy which includes the number of retry attempts for any failed request. Can be used instead of * {@link Ec2MetadataClientBuilder#retryPolicy(Ec2MetadataRetryPolicy)} to use a "fluent consumer" syntax. User * <em>should not</em> manually build the builder in the consumer. * <p> * If not specified, defaults to 3 retry attempts and a {@link BackoffStrategy#defaultStrategy()} backoff strategy} that * uses {@link RetryMode#STANDARD}. Can be also specified by using the * {@link Ec2MetadataClientBuilder#retryPolicy(Ec2MetadataRetryPolicy)} method. if any of the retryPolicy methods are * called multiple times, only the last invocation will be considered. * * @param builderConsumer the consumer * @return a reference to this builder */ B retryPolicy(Consumer<Ec2MetadataRetryPolicy.Builder> builderConsumer); /** * Define the endpoint of IMDS. * <p> * If not specified, the IMDS client will attempt to automatically resolve the endpoint value * based on the logic of {@link Ec2MetadataEndpointProvider}. * * @param endpoint The endpoint of IMDS. * @return a reference to this builder */ B endpoint(URI endpoint); /** * Define the Time to live (TTL) of the token. The token represents a logical session. The TTL specifies the length of time * that the token is valid and, therefore, the duration of the session. Defaults to 21,600 seconds (6 hours) if not specified. * * @param tokenTtl The Time to live (TTL) of the token. * @return a reference to this builder */ B tokenTtl(Duration tokenTtl); /** * Define the endpoint mode of IMDS. Supported values include IPv4 and IPv6. Used to determine the endpoint of the IMDS * Client only if {@link Ec2MetadataClientBuilder#endpoint(URI)} is not specified. Only one of both endpoint or endpoint mode * but not both. If both are specified in the Builder, a {@link IllegalArgumentException} will be thrown. * <p> * If not specified, the IMDS client will attempt to automatically resolve the endpoint mode value * based on the logic of {@link Ec2MetadataEndpointProvider}. * * @param endpointMode The endpoint mode of IMDS. Supported values include IPv4 and IPv6. * @return a reference to this builder */ B endpointMode(EndpointMode endpointMode); }
1,631
0
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds/Ec2MetadataAsyncClient.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.imds.internal.DefaultEc2MetadataAsyncClient; import software.amazon.awssdk.utils.SdkAutoCloseable; /** * Interface to represent the Ec2Metadata Client Class. Used to access instance metadata from a running EC2 instance. * <h2>Instantiate the Ec2MetadataAsyncClient</h2> * <h3>Default configuration</h3> * {@snippet : * Ec2MetadataAsyncClient client = Ec2MetadataAsyncClient.create(); * } * <h3>Custom configuration</h3> * Example of a client configured for using IPV6 and a fixed delay for retry attempts : * {@snippet : * Ec2MetadataAsyncClient client = Ec2MetadataAsyncClient.builder() * .retryPolicy(p -> p.backoffStrategy(FixedDelayBackoffStrategy.create(Duration.ofMillis(500)))) * .endpointMode(EndpointMode.IPV6) * .build(); * } * <h2>Use the client</h2> * Call the {@code get} method on the client with a path to an instance metadata: * {@snippet : * Ec2MetadataAsyncClient client = Ec2MetadataAsyncClient.create(); * CompletableFuture<Ec2MetadataResponse> response = client.get("/latest/meta-data/"); * response.thenAccept(System.out::println); * } * <h2>Closing the client</h2> * Once all operations are done, you may close the client to free any resources used by it. * {@snippet : * Ec2MetadataAsyncClient client = Ec2MetadataAsyncClient.create(); * // ... do the things * client.close(); * } * <br/>Note: A single client instance should be reused for multiple requests when possible. */ @SdkPublicApi public interface Ec2MetadataAsyncClient extends SdkAutoCloseable { /** * Gets the specified instance metadata value by the given path. For more information about instance metadata, check the * <a href=https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html>Instance metadata documentation</a>. * * @param path Input path * @return A CompletableFuture that completes when the MetadataResponse is made available. */ CompletableFuture<Ec2MetadataResponse> get(String path); /** * Create an {@link Ec2MetadataAsyncClient} instance using the default values. * * @return the client instance. */ static Ec2MetadataAsyncClient create() { return builder().build(); } /** * Creates a builder for an async client instance. * @return the newly created builder instance. */ static Ec2MetadataAsyncClient.Builder builder() { return DefaultEc2MetadataAsyncClient.builder(); } /** * The builder definition for a {@link Ec2MetadataClient}. All parameters are optional and have default values if not * specified. Therefore, an instance can be simply created with {@code Ec2MetadataAsyncClient.builder().build()} or * {@code Ec2MetadataAsyncClient.create()}, both having the same result. */ interface Builder extends Ec2MetadataClientBuilder<Ec2MetadataAsyncClient.Builder, Ec2MetadataAsyncClient> { /** * Define the {@link ScheduledExecutorService} used to schedule asynchronous retry attempts. If provided, the * Ec2MetadataClient will <em>NOT</em> manage the lifetime if the httpClient and must therefore be * closed explicitly by calling the {@link SdkAsyncHttpClient#close()} method on it. * <p> * If not specified, defaults to {@link Executors#newScheduledThreadPool} with a default value of 3 thread in the * pool. * * @param scheduledExecutorService the ScheduledExecutorService to use for retry attempt. * @return a reference to this builder */ Builder scheduledExecutorService(ScheduledExecutorService scheduledExecutorService); /** * Define the http client used by the Ec2 Metadata client. If provided, the Ec2MetadataClient will <em>NOT</em> manage the * lifetime if the httpClient and must therefore be closed explicitly by calling the {@link SdkAsyncHttpClient#close()} * method on it. * <p> * If not specified, the IMDS client will look for a SdkAsyncHttpClient class included in the classpath of the * application and creates a new instance of that class, managed by the IMDS Client, that will be closed when the IMDS * Client is closed. If no such class can be found, will throw a {@link SdkClientException}. * * @param httpClient the http client * @return a reference to this builder */ Builder httpClient(SdkAsyncHttpClient httpClient); /** * An http client builder used to retrieve an instance of an {@link SdkAsyncHttpClient}. If specified, the Ec2 * Metadata Client will use the instance returned by the builder and manage its lifetime by closing the http client * once the Ec2 Client itself is closed. * * @param builder the builder to used to retrieve an instance. * @return a reference to this builder */ Builder httpClient(SdkAsyncHttpClient.Builder<?> builder); } }
1,632
0
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds/internal/DefaultEc2MetadataAsyncClient.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds.internal; import static software.amazon.awssdk.imds.internal.AsyncHttpRequestHelper.sendAsyncTokenRequest; import java.net.URI; import java.time.Duration; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.internal.http.loader.DefaultSdkAsyncHttpClientBuilder; import software.amazon.awssdk.core.retry.RetryPolicyContext; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.imds.Ec2MetadataAsyncClient; import software.amazon.awssdk.imds.Ec2MetadataResponse; import software.amazon.awssdk.imds.Ec2MetadataRetryPolicy; import software.amazon.awssdk.imds.EndpointMode; import software.amazon.awssdk.utils.CompletableFutureUtils; import software.amazon.awssdk.utils.Either; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.ThreadFactoryBuilder; import software.amazon.awssdk.utils.Validate; @SdkInternalApi @Immutable @ThreadSafe public final class DefaultEc2MetadataAsyncClient extends BaseEc2MetadataClient implements Ec2MetadataAsyncClient { private static final Logger log = Logger.loggerFor(DefaultEc2MetadataClient.class); private static final int DEFAULT_RETRY_THREAD_POOL_SIZE = 3; private final SdkAsyncHttpClient httpClient; private final ScheduledExecutorService asyncRetryScheduler; private final boolean httpClientIsInternal; private final boolean retryExecutorIsInternal; private final AsyncTokenCache tokenCache; private DefaultEc2MetadataAsyncClient(Ec2MetadataAsyncBuilder builder) { super(builder); Validate.isTrue(builder.httpClient == null || builder.httpClientBuilder == null, "The httpClient and the httpClientBuilder can't both be configured."); this.httpClient = Either .fromNullable(builder.httpClient, builder.httpClientBuilder) .map(e -> e.map(Function.identity(), SdkAsyncHttpClient.Builder::build)) .orElseGet(() -> new DefaultSdkAsyncHttpClientBuilder().buildWithDefaults(IMDS_HTTP_DEFAULTS)); this.httpClientIsInternal = builder.httpClient == null; this.asyncRetryScheduler = Validate.getOrDefault( builder.scheduledExecutorService, () -> { ThreadFactory threadFactory = new ThreadFactoryBuilder().threadNamePrefix("IMDS-ScheduledExecutor").build(); return Executors.newScheduledThreadPool(DEFAULT_RETRY_THREAD_POOL_SIZE, threadFactory); }); this.retryExecutorIsInternal = builder.scheduledExecutorService == null; Supplier<CompletableFuture<Token>> tokenSupplier = () -> { SdkHttpFullRequest baseTokenRequest = requestMarshaller.createTokenRequest(tokenTtl); return sendAsyncTokenRequest(httpClient, baseTokenRequest); }; this.tokenCache = new AsyncTokenCache(tokenSupplier); } public static Ec2MetadataAsyncClient.Builder builder() { return new DefaultEc2MetadataAsyncClient.Ec2MetadataAsyncBuilder(); } @Override public CompletableFuture<Ec2MetadataResponse> get(String path) { CompletableFuture<Ec2MetadataResponse> returnFuture = new CompletableFuture<>(); get(path, RetryPolicyContext.builder().retriesAttempted(0).build(), returnFuture); return returnFuture; } private void get(String path, RetryPolicyContext retryPolicyContext, CompletableFuture<Ec2MetadataResponse> returnFuture) { CompletableFuture<Token> tokenFuture = tokenCache.get(); CompletableFuture<Ec2MetadataResponse> result = tokenFuture.thenCompose(token -> { SdkHttpFullRequest baseMetadataRequest = requestMarshaller.createDataRequest(path, token.value(), tokenTtl); return AsyncHttpRequestHelper.sendAsyncMetadataRequest(httpClient, baseMetadataRequest, returnFuture); }).thenApply(Ec2MetadataResponse::create); CompletableFutureUtils.forwardExceptionTo(returnFuture, result); result.whenComplete((response, error) -> { if (response != null) { returnFuture.complete(response); return; } if (!shouldRetry(retryPolicyContext, error)) { returnFuture.completeExceptionally(error); return; } int newAttempt = retryPolicyContext.retriesAttempted() + 1; log.debug(() -> "Retrying request: Attempt " + newAttempt); RetryPolicyContext newContext = RetryPolicyContext.builder() .retriesAttempted(newAttempt) .exception(SdkClientException.create(error.getMessage(), error)) .build(); scheduledRetryAttempt(() -> get(path, newContext, returnFuture), newContext); }); } private void scheduledRetryAttempt(Runnable runnable, RetryPolicyContext retryPolicyContext) { Duration retryDelay = retryPolicy.backoffStrategy().computeDelayBeforeNextRetry(retryPolicyContext); Executor retryExecutor = retryAttempt -> asyncRetryScheduler.schedule(retryAttempt, retryDelay.toMillis(), TimeUnit.MILLISECONDS); CompletableFuture.runAsync(runnable, retryExecutor); } @Override public void close() { if (httpClientIsInternal) { httpClient.close(); } if (retryExecutorIsInternal) { asyncRetryScheduler.shutdown(); } } protected static final class Ec2MetadataAsyncBuilder implements Ec2MetadataAsyncClient.Builder { private Ec2MetadataRetryPolicy retryPolicy; private URI endpoint; private Duration tokenTtl; private EndpointMode endpointMode; private SdkAsyncHttpClient httpClient; private SdkAsyncHttpClient.Builder<?> httpClientBuilder; private ScheduledExecutorService scheduledExecutorService; private Ec2MetadataAsyncBuilder() { } @Override public Ec2MetadataAsyncBuilder retryPolicy(Ec2MetadataRetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } @Override public Ec2MetadataAsyncBuilder retryPolicy(Consumer<Ec2MetadataRetryPolicy.Builder> builderConsumer) { Validate.notNull(builderConsumer, "builderConsumer must not be null"); Ec2MetadataRetryPolicy.Builder builder = Ec2MetadataRetryPolicy.builder(); builderConsumer.accept(builder); this.retryPolicy = builder.build(); return this; } @Override public Ec2MetadataAsyncBuilder endpoint(URI endpoint) { this.endpoint = endpoint; return this; } @Override public Ec2MetadataAsyncBuilder tokenTtl(Duration tokenTtl) { this.tokenTtl = tokenTtl; return this; } @Override public Ec2MetadataAsyncBuilder endpointMode(EndpointMode endpointMode) { this.endpointMode = endpointMode; return this; } @Override public Ec2MetadataAsyncBuilder httpClient(SdkAsyncHttpClient httpClient) { this.httpClient = httpClient; return this; } @Override public Builder httpClient(SdkAsyncHttpClient.Builder<?> builder) { this.httpClientBuilder = builder; return this; } @Override public Ec2MetadataAsyncBuilder scheduledExecutorService(ScheduledExecutorService scheduledExecutorService) { this.scheduledExecutorService = scheduledExecutorService; return this; } public Ec2MetadataRetryPolicy getRetryPolicy() { return this.retryPolicy; } public URI getEndpoint() { return this.endpoint; } public Duration getTokenTtl() { return this.tokenTtl; } public EndpointMode getEndpointMode() { return this.endpointMode; } @Override public Ec2MetadataAsyncClient build() { return new DefaultEc2MetadataAsyncClient(this); } } }
1,633
0
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds/internal/DefaultEc2MetadataClient.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds.internal; import static software.amazon.awssdk.imds.internal.RequestMarshaller.EC2_METADATA_TOKEN_TTL_HEADER; import java.io.IOException; import java.io.UncheckedIOException; import java.net.URI; import java.time.Duration; import java.time.Instant; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.core.exception.RetryableException; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.internal.http.loader.DefaultSdkHttpClientBuilder; import software.amazon.awssdk.core.retry.RetryPolicyContext; import software.amazon.awssdk.http.AbortableInputStream; import software.amazon.awssdk.http.HttpExecuteRequest; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.HttpStatusFamily; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.imds.Ec2MetadataClient; import software.amazon.awssdk.imds.Ec2MetadataResponse; import software.amazon.awssdk.imds.Ec2MetadataRetryPolicy; import software.amazon.awssdk.imds.EndpointMode; import software.amazon.awssdk.utils.Either; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.cache.CachedSupplier; import software.amazon.awssdk.utils.cache.RefreshResult; /** * An Implementation of the Ec2Metadata Interface. */ @SdkInternalApi @Immutable @ThreadSafe public final class DefaultEc2MetadataClient extends BaseEc2MetadataClient implements Ec2MetadataClient { private static final Logger log = Logger.loggerFor(DefaultEc2MetadataClient.class); private final SdkHttpClient httpClient; private final Supplier<Token> tokenCache; private final boolean httpClientIsInternal; private DefaultEc2MetadataClient(Ec2MetadataBuilder builder) { super(builder); Validate.isTrue(builder.httpClient == null || builder.httpClientBuilder == null, "The httpClient and the httpClientBuilder can't both be configured."); this.httpClient = Either .fromNullable(builder.httpClient, builder.httpClientBuilder) .map(e -> e.map(Function.identity(), SdkHttpClient.Builder::build)) .orElseGet(() -> new DefaultSdkHttpClientBuilder().buildWithDefaults(IMDS_HTTP_DEFAULTS)); this.httpClientIsInternal = builder.httpClient == null; this.tokenCache = CachedSupplier.builder(() -> RefreshResult.builder(this.getToken()) .staleTime(Instant.now().plus(tokenTtl)) .build()) .cachedValueName(toString()) .build(); } @Override public String toString() { return ToString.create("Ec2MetadataClient"); } @Override public void close() { if (httpClientIsInternal) { httpClient.close(); } } public static Ec2MetadataBuilder builder() { return new DefaultEc2MetadataClient.Ec2MetadataBuilder(); } /** * Gets the specified instance metadata value by the given path. Will retry base on the * {@link Ec2MetadataRetryPolicy retry policy} provided, in the case of an IOException during request. Will not retry on * SdkClientException, like 4XX HTTP error. * * @param path Input path of the resource to get. * @return Instance metadata value as part of MetadataResponse Object * @throws SdkClientException if the request for a token or the request for the Metadata does not have a 2XX SUCCESS response, * if the maximum number of retries is reached, or if another IOException is thrown during the * request. */ @Override public Ec2MetadataResponse get(String path) { Throwable lastCause = null; // 3 retries means 4 total attempts Token token = null; for (int attempt = 0; attempt < retryPolicy.numRetries() + 1; attempt++) { RetryPolicyContext retryPolicyContext = RetryPolicyContext.builder().retriesAttempted(attempt).build(); try { if (token == null || token.isExpired()) { token = tokenCache.get(); } return sendRequest(path, token.value()); } catch (UncheckedIOException | RetryableException e) { lastCause = e; int currentTry = attempt; log.debug(() -> "Error while executing EC2Metadata request, attempting retry. Current attempt: " + currentTry); } catch (SdkClientException sdkClientException) { int totalTries = attempt + 1; log.debug(() -> String.format("Error while executing EC2Metadata request. Total attempts: %d. %s", totalTries, sdkClientException.getMessage())); throw sdkClientException; } catch (IOException ioe) { lastCause = new UncheckedIOException(ioe); int currentTry = attempt; log.debug(() -> "Error while executing EC2Metadata request, attempting retry. Current attempt: " + currentTry); } pauseBeforeRetryIfNeeded(retryPolicyContext); } SdkClientException.Builder sdkClientExceptionBuilder = SdkClientException .builder() .message("Exceeded maximum number of retries. Total retry attempts: " + retryPolicy.numRetries()); if (lastCause != null) { String msg = sdkClientExceptionBuilder.message(); sdkClientExceptionBuilder.cause(lastCause).message(msg); } throw sdkClientExceptionBuilder.build(); } private Ec2MetadataResponse sendRequest(String path, String token) throws IOException { HttpExecuteRequest httpExecuteRequest = HttpExecuteRequest.builder() .request(requestMarshaller.createDataRequest(path, token, tokenTtl)) .build(); HttpExecuteResponse response = httpClient.prepareRequest(httpExecuteRequest).call(); int statusCode = response.httpResponse().statusCode(); Optional<AbortableInputStream> responseBody = response.responseBody(); if (HttpStatusFamily.of(statusCode).isOneOf(HttpStatusFamily.SERVER_ERROR)) { responseBody.map(BaseEc2MetadataClient::uncheckedInputStreamToUtf8) .ifPresent(str -> log.debug(() -> "Metadata request response body: " + str)); throw RetryableException .builder() .message(String.format("The requested metadata at path '%s' returned Http code %s", path, statusCode)) .build(); } if (!HttpStatusFamily.of(statusCode).isOneOf(HttpStatusFamily.SUCCESSFUL)) { responseBody.map(BaseEc2MetadataClient::uncheckedInputStreamToUtf8) .ifPresent(str -> log.debug(() -> "Metadata request response body: " + str)); throw SdkClientException .builder() .message(String.format("The requested metadata at path '%s' returned Http code %s", path, statusCode)) .build(); } AbortableInputStream abortableInputStream = responseBody.orElseThrow( SdkClientException.builder().message("Response body empty with Status Code " + statusCode)::build); String data = uncheckedInputStreamToUtf8(abortableInputStream); return Ec2MetadataResponse.create(data); } private void pauseBeforeRetryIfNeeded(RetryPolicyContext retryPolicyContext) { long backoffTimeMillis = retryPolicy.backoffStrategy() .computeDelayBeforeNextRetry(retryPolicyContext) .toMillis(); if (backoffTimeMillis > 0) { try { TimeUnit.MILLISECONDS.sleep(backoffTimeMillis); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw SdkClientException.builder().message("Thread interrupted while trying to sleep").cause(e).build(); } } } private Token getToken() { HttpExecuteRequest httpExecuteRequest = HttpExecuteRequest.builder() .request(requestMarshaller.createTokenRequest(tokenTtl)) .build(); HttpExecuteResponse response = null; try { response = httpClient.prepareRequest(httpExecuteRequest).call(); } catch (IOException e) { throw new UncheckedIOException(e); } int statusCode = response.httpResponse().statusCode(); if (HttpStatusFamily.of(statusCode).isOneOf(HttpStatusFamily.SERVER_ERROR)) { response.responseBody().map(BaseEc2MetadataClient::uncheckedInputStreamToUtf8) .ifPresent(str -> log.debug(() -> "Metadata request response body: " + str)); throw RetryableException.builder() .message("Could not retrieve token, " + statusCode + " error occurred").build(); } if (!HttpStatusFamily.of(statusCode).isOneOf(HttpStatusFamily.SUCCESSFUL)) { response.responseBody().map(BaseEc2MetadataClient::uncheckedInputStreamToUtf8) .ifPresent(body -> log.debug(() -> "Token request response body: " + body)); throw SdkClientException.builder() .message("Could not retrieve token, " + statusCode + " error occurred.") .build(); } String ttl = response.httpResponse() .firstMatchingHeader(EC2_METADATA_TOKEN_TTL_HEADER) .orElseThrow(() -> SdkClientException .builder() .message(EC2_METADATA_TOKEN_TTL_HEADER + " header not found in token response") .build()); Duration ttlDuration; try { ttlDuration = Duration.ofSeconds(Long.parseLong(ttl)); } catch (NumberFormatException nfe) { throw SdkClientException.create("Invalid token format received from IMDS server", nfe); } AbortableInputStream abortableInputStream = response.responseBody().orElseThrow( SdkClientException.builder().message("Empty response body")::build); String value = uncheckedInputStreamToUtf8(abortableInputStream); return new Token(value, ttlDuration); } protected static final class Ec2MetadataBuilder implements Ec2MetadataClient.Builder { private Ec2MetadataRetryPolicy retryPolicy; private URI endpoint; private Duration tokenTtl; private EndpointMode endpointMode; private SdkHttpClient httpClient; private SdkHttpClient.Builder<?> httpClientBuilder; private Ec2MetadataBuilder() { } @Override public Ec2MetadataBuilder retryPolicy(Ec2MetadataRetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } @Override public Builder retryPolicy(Consumer<Ec2MetadataRetryPolicy.Builder> builderConsumer) { Validate.notNull(builderConsumer, "builderConsumer must not be null"); Ec2MetadataRetryPolicy.Builder builder = Ec2MetadataRetryPolicy.builder(); builderConsumer.accept(builder); return retryPolicy(builder.build()); } @Override public Ec2MetadataBuilder endpoint(URI endpoint) { this.endpoint = endpoint; return this; } @Override public Ec2MetadataBuilder tokenTtl(Duration tokenTtl) { this.tokenTtl = tokenTtl; return this; } @Override public Ec2MetadataBuilder endpointMode(EndpointMode endpointMode) { this.endpointMode = endpointMode; return this; } @Override public Ec2MetadataBuilder httpClient(SdkHttpClient httpClient) { this.httpClient = httpClient; return this; } @Override public Builder httpClient(SdkHttpClient.Builder<?> builder) { this.httpClientBuilder = builder; return this; } public Ec2MetadataRetryPolicy getRetryPolicy() { return this.retryPolicy; } public URI getEndpoint() { return this.endpoint; } public Duration getTokenTtl() { return this.tokenTtl; } public EndpointMode getEndpointMode() { return this.endpointMode; } @Override public Ec2MetadataClient build() { return new DefaultEc2MetadataClient(this); } } }
1,634
0
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds/internal/BaseEc2MetadataClient.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds.internal; import java.io.IOException; import java.io.UncheckedIOException; import java.net.URI; import java.time.Duration; import java.time.temporal.ChronoUnit; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.exception.RetryableException; import software.amazon.awssdk.core.retry.RetryPolicyContext; import software.amazon.awssdk.http.AbortableInputStream; import software.amazon.awssdk.http.SdkHttpConfigurationOption; import software.amazon.awssdk.imds.Ec2MetadataRetryPolicy; import software.amazon.awssdk.imds.EndpointMode; import software.amazon.awssdk.utils.AttributeMap; import software.amazon.awssdk.utils.IoUtils; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; @SdkInternalApi public abstract class BaseEc2MetadataClient { protected static final Duration DEFAULT_TOKEN_TTL = Duration.of(21_600, ChronoUnit.SECONDS); protected static final AttributeMap IMDS_HTTP_DEFAULTS = AttributeMap.builder() .put(SdkHttpConfigurationOption.CONNECTION_TIMEOUT, Duration.ofSeconds(1)) .put(SdkHttpConfigurationOption.READ_TIMEOUT, Duration.ofSeconds(1)) .build(); private static final Logger log = Logger.loggerFor(BaseEc2MetadataClient.class); protected final Ec2MetadataRetryPolicy retryPolicy; protected final URI endpoint; protected final RequestMarshaller requestMarshaller; protected final Duration tokenTtl; private BaseEc2MetadataClient(Ec2MetadataRetryPolicy retryPolicy, Duration tokenTtl, URI endpoint, EndpointMode endpointMode) { this.retryPolicy = Validate.getOrDefault(retryPolicy, Ec2MetadataRetryPolicy.builder()::build); this.tokenTtl = Validate.getOrDefault(tokenTtl, () -> DEFAULT_TOKEN_TTL); this.endpoint = getEndpoint(endpoint, endpointMode); this.requestMarshaller = new RequestMarshaller(this.endpoint); } protected BaseEc2MetadataClient(DefaultEc2MetadataClient.Ec2MetadataBuilder builder) { this(builder.getRetryPolicy(), builder.getTokenTtl(), builder.getEndpoint(), builder.getEndpointMode()); } protected BaseEc2MetadataClient(DefaultEc2MetadataAsyncClient.Ec2MetadataAsyncBuilder builder) { this(builder.getRetryPolicy(), builder.getTokenTtl(), builder.getEndpoint(), builder.getEndpointMode()); } private URI getEndpoint(URI builderEndpoint, EndpointMode builderEndpointMode) { Validate.mutuallyExclusive("Only one of 'endpoint' or 'endpointMode' must be specified, but not both", builderEndpoint, builderEndpointMode); if (builderEndpoint != null) { return builderEndpoint; } if (builderEndpointMode != null) { return URI.create(Ec2MetadataEndpointProvider.instance().resolveEndpoint(builderEndpointMode)); } EndpointMode resolvedEndpointMode = Ec2MetadataEndpointProvider.instance().resolveEndpointMode(); return URI.create(Ec2MetadataEndpointProvider.instance().resolveEndpoint(resolvedEndpointMode)); } protected static String uncheckedInputStreamToUtf8(AbortableInputStream inputStream) { try { return IoUtils.toUtf8String(inputStream); } catch (IOException ioe) { throw new UncheckedIOException(ioe); } finally { IoUtils.closeQuietly(inputStream, log.logger()); } } protected boolean shouldRetry(RetryPolicyContext retryPolicyContext, Throwable error) { boolean maxAttemptReached = retryPolicyContext.retriesAttempted() >= retryPolicy.numRetries(); if (maxAttemptReached) { return false; } return error instanceof RetryableException || error.getCause() instanceof RetryableException; } }
1,635
0
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds/internal/Ec2MetadataEndpointProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds.internal; import static software.amazon.awssdk.imds.EndpointMode.IPV4; import static software.amazon.awssdk.imds.EndpointMode.IPV6; import java.util.EnumMap; import java.util.Optional; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.imds.EndpointMode; import software.amazon.awssdk.profiles.Profile; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileFileSystemSetting; import software.amazon.awssdk.profiles.ProfileProperty; import software.amazon.awssdk.utils.Validate; /** * Endpoint Provider Class which contains methods for endpoint resolution. */ @SdkInternalApi public final class Ec2MetadataEndpointProvider { private static final Ec2MetadataEndpointProvider DEFAULT_ENDPOINT_PROVIDER = builder().build(); private static final EnumMap<EndpointMode, String> DEFAULT_ENDPOINT_MODE; static { DEFAULT_ENDPOINT_MODE = new EnumMap<>(EndpointMode.class); DEFAULT_ENDPOINT_MODE.put(IPV4, "http://169.254.169.254"); DEFAULT_ENDPOINT_MODE.put(IPV6, "http://[fd00:ec2::254]"); } private final Supplier<ProfileFile> profileFile; private final String profileName; private Ec2MetadataEndpointProvider(Builder builder) { this.profileFile = builder.profileFile; this.profileName = builder.profileName; } public static Ec2MetadataEndpointProvider instance() { return DEFAULT_ENDPOINT_PROVIDER; } /** * Resolve the endpoint to be used for the {@link DefaultEc2MetadataClient} client. Users may manually provide an endpoint * through the {@code AWS_EC2_METADATA_SERVICE_ENDPOINT} environment variable or the {@code ec2_metadata_service_endpoint} * key in their aws config file. * If an endpoint is specified is this manner, use it. If no values are provided, the defaults to: * <ol> * <li>If endpoint mode is set to IPv4: {@code "http://169.254.169.254"}</li> * <li>If endpoint mode is set to IPv6: {@code "http://[fd00:ec2::254]"}</li> * </ol> * (the default endpoint mode is IPV4). * @param endpointMode Used only if an endpoint value is not specified. If so, this method will use the endpointMode to * choose the default value to return. * @return the String representing the endpoint to be used, */ public String resolveEndpoint(EndpointMode endpointMode) { Optional<String> endpointFromSystem = SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.getNonDefaultStringValue(); if (endpointFromSystem.isPresent()) { return stripEndingSlash(endpointFromSystem.get()); } Optional<String> endpointFromConfigProfile = resolveProfile() .flatMap(profile -> profile.property(ProfileProperty.EC2_METADATA_SERVICE_ENDPOINT)); if (endpointFromConfigProfile.isPresent()) { return stripEndingSlash(endpointFromConfigProfile.get()); } Validate.notNull(endpointMode, "endpointMode must not be null."); return endpointFromConfigProfile.orElseGet(() -> DEFAULT_ENDPOINT_MODE.get(endpointMode)); } private static String stripEndingSlash(String uri) { return uri.endsWith("/") ? uri.substring(0, uri.length() - 1) : uri; } public EndpointMode resolveEndpointMode() { Optional<String> systemEndpointMode = SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE.getNonDefaultStringValue(); if (systemEndpointMode.isPresent()) { return EndpointMode.fromValue(systemEndpointMode.get()); } Optional<EndpointMode> configFileEndPointMode = resolveProfile() .flatMap(p -> p.property(ProfileProperty.EC2_METADATA_SERVICE_ENDPOINT_MODE)) .map(EndpointMode::fromValue); if (configFileEndPointMode.isPresent()) { return configFileEndPointMode.get(); } String defaultSystemEndpointMode = SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE.defaultValue(); return EndpointMode.fromValue(defaultSystemEndpointMode); } public Optional<Profile> resolveProfile() { String profileNameToUse = profileName == null ? ProfileFileSystemSetting.AWS_PROFILE.getStringValueOrThrow() : profileName; ProfileFile profileFileToUse = profileFile.get(); return profileFileToUse.profile(profileNameToUse); } public static Builder builder() { return new Builder(); } public static final class Builder { private Supplier<ProfileFile> profileFile; private String profileName; private Builder() { this.profileFile = ProfileFile::defaultProfileFile; } public Builder profileFile(Supplier<ProfileFile> profileFile) { Validate.notNull(profileFile, "profileFile Supplier must not be null"); this.profileFile = profileFile; return this; } public Builder profileName(String profileName) { this.profileName = profileName; return this; } public Ec2MetadataEndpointProvider build() { return new Ec2MetadataEndpointProvider(this); } } }
1,636
0
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds/internal/AsyncHttpRequestHelper.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds.internal; import static software.amazon.awssdk.imds.internal.BaseEc2MetadataClient.uncheckedInputStreamToUtf8; import static software.amazon.awssdk.imds.internal.RequestMarshaller.EC2_METADATA_TOKEN_TTL_HEADER; import java.time.Duration; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.exception.RetryableException; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.internal.http.TransformingAsyncResponseHandler; import software.amazon.awssdk.core.internal.http.async.AsyncResponseHandler; import software.amazon.awssdk.core.internal.http.async.SimpleHttpContentPublisher; import software.amazon.awssdk.http.AbortableInputStream; import software.amazon.awssdk.http.HttpStatusFamily; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.http.async.AsyncExecuteRequest; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.http.async.SdkHttpContentPublisher; import software.amazon.awssdk.utils.CompletableFutureUtils; @SdkInternalApi final class AsyncHttpRequestHelper { private AsyncHttpRequestHelper() { // static utility class } public static CompletableFuture<String> sendAsyncMetadataRequest(SdkAsyncHttpClient httpClient, SdkHttpFullRequest baseRequest, CompletableFuture<?> parentFuture) { return sendAsync(httpClient, baseRequest, AsyncHttpRequestHelper::handleResponse, parentFuture); } public static CompletableFuture<Token> sendAsyncTokenRequest(SdkAsyncHttpClient httpClient, SdkHttpFullRequest baseRequest) { return sendAsync(httpClient, baseRequest, AsyncHttpRequestHelper::handleTokenResponse, null); } private static <T> CompletableFuture<T> sendAsync(SdkAsyncHttpClient client, SdkHttpFullRequest request, HttpResponseHandler<T> handler, CompletableFuture<?> parentFuture) { SdkHttpContentPublisher requestContentPublisher = new SimpleHttpContentPublisher(request); TransformingAsyncResponseHandler<T> responseHandler = new AsyncResponseHandler<>(handler, Function.identity(), new ExecutionAttributes()); CompletableFuture<T> responseHandlerFuture = responseHandler.prepare(); AsyncExecuteRequest metadataRequest = AsyncExecuteRequest.builder() .request(request) .requestContentPublisher(requestContentPublisher) .responseHandler(responseHandler) .build(); CompletableFuture<Void> executeFuture = client.execute(metadataRequest); if (parentFuture != null) { CompletableFutureUtils.forwardExceptionTo(parentFuture, executeFuture); CompletableFutureUtils.forwardExceptionTo(parentFuture, responseHandlerFuture); } return responseHandlerFuture; } private static String handleResponse(SdkHttpFullResponse response, ExecutionAttributes executionAttributes) { HttpStatusFamily statusCode = HttpStatusFamily.of(response.statusCode()); AbortableInputStream inputStream = response.content().orElseThrow(() -> SdkClientException.create("Unexpected error: empty response content")); String responseContent = uncheckedInputStreamToUtf8(inputStream); // non-retryable error if (statusCode.isOneOf(HttpStatusFamily.CLIENT_ERROR)) { throw SdkClientException.builder().message(responseContent).build(); } // retryable error if (statusCode.isOneOf(HttpStatusFamily.SERVER_ERROR)) { throw RetryableException.create(responseContent); } return responseContent; } private static Token handleTokenResponse(SdkHttpFullResponse response, ExecutionAttributes executionAttributes) { String tokenValue = handleResponse(response, executionAttributes); Optional<String> ttl = response.firstMatchingHeader(EC2_METADATA_TOKEN_TTL_HEADER); if (!ttl.isPresent()) { throw SdkClientException.create(EC2_METADATA_TOKEN_TTL_HEADER + " header not found in token response"); } try { Duration ttlDuration = Duration.ofSeconds(Long.parseLong(ttl.get())); return new Token(tokenValue, ttlDuration); } catch (NumberFormatException nfe) { throw SdkClientException.create( "Invalid token format received from IMDS server. Token received: " + tokenValue, nfe); } } }
1,637
0
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds/internal/Token.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds.internal; import java.time.Duration; import java.time.Instant; import java.util.Objects; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.utils.ToString; @SdkInternalApi @Immutable public final class Token { private final String value; private final Duration ttl; private final Instant createdTime; public Token(String value, Duration ttl) { this.value = value; this.ttl = ttl; this.createdTime = Instant.now(); } public String value() { return value; } public Duration ttl() { return ttl; } public Instant createdTime() { return createdTime; } public boolean isExpired() { return Instant.now().isAfter(createdTime.plus(ttl)); } @Override public String toString() { return ToString.builder("Token") .add("value", value) .add("ttl", ttl) .add("createdTime", createdTime) .build(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Token token = (Token) o; if (!Objects.equals(value, token.value)) { return false; } if (!Objects.equals(ttl, token.ttl)) { return false; } return Objects.equals(createdTime, token.createdTime); } @Override public int hashCode() { int result = value != null ? value.hashCode() : 0; result = 31 * result + (ttl != null ? ttl.hashCode() : 0); result = 31 * result + (createdTime != null ? createdTime.hashCode() : 0); return result; } }
1,638
0
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds/internal/AsyncTokenCache.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds.internal; import java.util.ArrayList; import java.util.Collection; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.utils.Logger; /** * A cache for the IMDS {@link Token}, which can be refreshed through an asynchronous operation. * A call to the {@link AsyncTokenCache#get()} method returns an already completed future if the cached token is still fresh. * If the cached token was expired, the returned future will be completed once the refresh process has been * completed. * In the case where multiple call to <pre>get</pre> are made while the token is expired, all CompletableFuture returned * will be completed once the single refresh process completes. * */ @SdkInternalApi final class AsyncTokenCache implements Supplier<CompletableFuture<Token>> { private static final Logger log = Logger.loggerFor(AsyncTokenCache.class); /** * The currently cached value. * Only modified through synchronized block, under the refreshLock. */ private volatile Token cachedToken; /** * The asynchronous operation that is used to refresh the token. * The Supplier must not block the current thread and is responsible to start the process that will complete the future. * A call the {@link AsyncTokenCache#get} method does not join or wait for the supplied future to finish, it only refreshes * the token once it finishes. */ private final Supplier<CompletableFuture<Token>> supplier; /** * The collection of future that are waiting for the refresh call to complete. If a call to {@link AsyncTokenCache#get()} * is made while the token request is happening, a future will be added to this collection. All future in this collection * are completed once the token request is done. * Should only be modified while holding the lock on {@link AsyncTokenCache#refreshLock}. */ private Collection<CompletableFuture<Token>> waitingFutures = new ArrayList<>(); /** * Indicates if the token refresh request is currently running or not. */ private final AtomicBoolean refreshRunning = new AtomicBoolean(false); private final Object refreshLock = new Object(); AsyncTokenCache(Supplier<CompletableFuture<Token>> supplier) { this.supplier = supplier; } @Override public CompletableFuture<Token> get() { Token currentValue = cachedToken; if (!needsRefresh(currentValue)) { log.debug(() -> "IMDS Token is not expired"); return CompletableFuture.completedFuture(currentValue); } synchronized (refreshLock) { // Make sure the value wasn't refreshed while we were waiting for the lock. currentValue = cachedToken; if (!needsRefresh(currentValue)) { return CompletableFuture.completedFuture(currentValue); } CompletableFuture<Token> result = new CompletableFuture<>(); waitingFutures.add(result); if (!refreshRunning.get()) { startRefresh(); } return result; } } private void startRefresh() { log.debug(() -> "IMDS token expired or null, starting asynchronous refresh."); CompletableFuture<Token> tokenRequest = supplier.get(); refreshRunning.set(true); // After supplier.get(), in case that throws an exception tokenRequest.whenComplete((token, throwable) -> { Collection<CompletableFuture<Token>> toComplete; synchronized (refreshLock) { // Instead of completing the waiting future while holding the lock, we copy the list reference and // release the lock before completing them. This is just in case someone (naughty) is doing something // blocking on the complete calls. It's not good that they're doing that, but at least // it won't block other threads trying to acquire the lock. toComplete = waitingFutures; waitingFutures = new ArrayList<>(); refreshRunning.set(false); if (token != null) { log.debug(() -> "IMDS token refresh completed. Token value: " + token.value()); cachedToken = token; } else { log.error(() -> "IMDS token refresh completed with error.", throwable); } } toComplete.forEach(future -> { if (throwable == null) { future.complete(token); } else { future.completeExceptionally(throwable); } }); }); } private boolean needsRefresh(Token token) { return token == null || token.isExpired(); } }
1,639
0
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds/internal/RequestMarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds.internal; import java.net.URI; import java.time.Duration; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.util.SdkUserAgent; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; /** * Class to parse the parameters to a SdkHttpRequest, make the call to the endpoint and send the HttpExecuteResponse * to the DefaultEc2Metadata class for further processing. */ @SdkInternalApi public class RequestMarshaller { public static final String TOKEN_RESOURCE_PATH = "/latest/api/token"; public static final String TOKEN_HEADER = "x-aws-ec2-metadata-token"; public static final String EC2_METADATA_TOKEN_TTL_HEADER = "x-aws-ec2-metadata-token-ttl-seconds"; public static final String USER_AGENT = "user_agent"; public static final String ACCEPT = "Accept"; public static final String CONNECTION = "connection"; private final URI basePath; private final URI tokenPath; public RequestMarshaller(URI basePath) { this.basePath = basePath; this.tokenPath = URI.create(basePath + TOKEN_RESOURCE_PATH); } public SdkHttpFullRequest createTokenRequest(Duration tokenTtl) { return defaulttHttpBuilder() .method(SdkHttpMethod.PUT) .uri(tokenPath) .putHeader(EC2_METADATA_TOKEN_TTL_HEADER, String.valueOf(tokenTtl.getSeconds())) .build(); } public SdkHttpFullRequest createDataRequest(String path, String token, Duration tokenTtl) { URI resourcePath = URI.create(basePath + path); return defaulttHttpBuilder() .method(SdkHttpMethod.GET) .uri(resourcePath) .putHeader(EC2_METADATA_TOKEN_TTL_HEADER, String.valueOf(tokenTtl.getSeconds())) .putHeader(TOKEN_HEADER, token) .build(); } private SdkHttpFullRequest.Builder defaulttHttpBuilder() { return SdkHttpFullRequest.builder() .putHeader(USER_AGENT, SdkUserAgent.create().userAgent()) .putHeader(ACCEPT, "*/*") .putHeader(CONNECTION, "keep-alive"); } }
1,640
0
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds/internal/unmarshall
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds/internal/unmarshall/document/DocumentUnmarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds.internal.unmarshall.document; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.document.Document; import software.amazon.awssdk.protocols.jsoncore.JsonNode; import software.amazon.awssdk.protocols.jsoncore.JsonNodeVisitor; @SdkInternalApi public final class DocumentUnmarshaller implements JsonNodeVisitor<Document> { @Override public Document visitNull() { return Document.fromNull(); } @Override public Document visitBoolean(boolean bool) { return Document.fromBoolean(bool); } @Override public Document visitNumber(String number) { return Document.fromNumber(number); } @Override public Document visitString(String string) { return Document.fromString(string); } @Override public Document visitArray(List<JsonNode> array) { return Document.fromList(array.stream() .map(node -> node.visit(this)) .collect(Collectors.toList())); } @Override public Document visitObject(Map<String, JsonNode> object) { return Document.fromMap(object.entrySet() .stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().visit(this), (left, right) -> left, LinkedHashMap::new))); } @Override public Document visitEmbeddedObject(Object embeddedObject) { throw new UnsupportedOperationException("Embedded objects are not supported within Document types."); } }
1,641
0
Create_ds/aws-sdk-java-v2/core/crt-core/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/crt-core/src/test/java/software/amazon/awssdk/crtcore/CrtProxyConfigurationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.crtcore; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; class CrtProxyConfigurationTest { @Test void equalsHashCodeTest() { EqualsVerifier.forClass(CrtProxyConfiguration.class) .usingGetClass() .verify(); } }
1,642
0
Create_ds/aws-sdk-java-v2/core/crt-core/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/crt-core/src/test/java/software/amazon/awssdk/crtcore/CrtConnectionUtilsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.crtcore; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import java.time.Duration; import java.util.Optional; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import software.amazon.awssdk.crt.http.HttpMonitoringOptions; import software.amazon.awssdk.crt.http.HttpProxyOptions; import software.amazon.awssdk.crt.io.TlsContext; class CrtConnectionUtilsTest { @Test void resolveProxy_basicAuthorization() { CrtProxyConfiguration configuration = new TestProxy.Builder().host("1.2.3.4") .port(123) .scheme("https") .password("bar") .username("foo") .build(); TlsContext tlsContext = Mockito.mock(TlsContext.class); Optional<HttpProxyOptions> httpProxyOptions = CrtConfigurationUtils.resolveProxy(configuration, tlsContext); assertThat(httpProxyOptions).hasValueSatisfying(proxy -> { assertThat(proxy.getTlsContext()).isEqualTo(tlsContext); assertThat(proxy.getAuthorizationPassword()).isEqualTo("bar"); assertThat(proxy.getAuthorizationUsername()).isEqualTo("foo"); assertThat(proxy.getAuthorizationType()).isEqualTo(HttpProxyOptions.HttpProxyAuthorizationType.Basic); }); } @Test void resolveProxy_emptyProxy_shouldReturnEmpty() { TlsContext tlsContext = Mockito.mock(TlsContext.class); assertThat(CrtConfigurationUtils.resolveProxy(null, tlsContext)).isEmpty(); } @Test void resolveProxy_noneAuthorization() { CrtProxyConfiguration configuration = new TestProxy.Builder().host("1.2.3.4") .port(123) .build(); TlsContext tlsContext = Mockito.mock(TlsContext.class); Optional<HttpProxyOptions> httpProxyOptions = CrtConfigurationUtils.resolveProxy(configuration, tlsContext); assertThat(httpProxyOptions).hasValueSatisfying(proxy -> { assertThat(proxy.getTlsContext()).isNull(); assertThat(proxy.getAuthorizationPassword()).isNull(); assertThat(proxy.getAuthorizationUsername()).isNull(); assertThat(proxy.getAuthorizationType()).isEqualTo(HttpProxyOptions.HttpProxyAuthorizationType.None); }); } @Test void resolveHttpMonitoringOptions_shouldMap() { CrtConnectionHealthConfiguration configuration = new TestConnectionHealthConfiguration.Builder() .minimumThroughputInBps(123L) .minimumThroughputTimeout(Duration.ofSeconds(5)) .build(); Optional<HttpMonitoringOptions> options = CrtConfigurationUtils.resolveHttpMonitoringOptions(configuration); assertThat(options).hasValueSatisfying(proxy -> { assertThat(proxy.getAllowableThroughputFailureIntervalSeconds()).isEqualTo(5); assertThat(proxy.getMinThroughputBytesPerSecond()).isEqualTo(123L); }); } @Test void resolveHttpMonitoringOptions_nullConfig_shouldReturnEmpty() { assertThat(CrtConfigurationUtils.resolveHttpMonitoringOptions(null)).isEmpty(); } private static final class TestProxy extends CrtProxyConfiguration { private TestProxy(DefaultBuilder<?> builder) { super(builder); } private static final class Builder extends CrtProxyConfiguration.DefaultBuilder<Builder> { @Override public TestProxy build() { return new TestProxy(this); } } } private static final class TestConnectionHealthConfiguration extends CrtConnectionHealthConfiguration { private TestConnectionHealthConfiguration(DefaultBuilder<?> builder) { super(builder); } private static final class Builder extends CrtConnectionHealthConfiguration.DefaultBuilder<Builder> { @Override public TestConnectionHealthConfiguration build() { return new TestConnectionHealthConfiguration(this); } } } }
1,643
0
Create_ds/aws-sdk-java-v2/core/crt-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/crt-core/src/main/java/software/amazon/awssdk/crtcore/CrtConfigurationUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.crtcore; import java.util.Optional; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.crt.http.HttpMonitoringOptions; import software.amazon.awssdk.crt.http.HttpProxyOptions; import software.amazon.awssdk.crt.io.TlsContext; import software.amazon.awssdk.utils.NumericUtils; @SdkProtectedApi public final class CrtConfigurationUtils { private CrtConfigurationUtils() { } public static Optional<HttpProxyOptions> resolveProxy(CrtProxyConfiguration proxyConfiguration, TlsContext tlsContext) { if (proxyConfiguration == null) { return Optional.empty(); } HttpProxyOptions clientProxyOptions = new HttpProxyOptions(); clientProxyOptions.setHost(proxyConfiguration.host()); clientProxyOptions.setPort(proxyConfiguration.port()); if ("https".equalsIgnoreCase(proxyConfiguration.scheme())) { clientProxyOptions.setTlsContext(tlsContext); } if (proxyConfiguration.username() != null && proxyConfiguration.password() != null) { clientProxyOptions.setAuthorizationUsername(proxyConfiguration.username()); clientProxyOptions.setAuthorizationPassword(proxyConfiguration.password()); clientProxyOptions.setAuthorizationType(HttpProxyOptions.HttpProxyAuthorizationType.Basic); } else { clientProxyOptions.setAuthorizationType(HttpProxyOptions.HttpProxyAuthorizationType.None); } return Optional.of(clientProxyOptions); } public static Optional<HttpMonitoringOptions> resolveHttpMonitoringOptions(CrtConnectionHealthConfiguration config) { if (config == null) { return Optional.empty(); } HttpMonitoringOptions httpMonitoringOptions = new HttpMonitoringOptions(); httpMonitoringOptions.setMinThroughputBytesPerSecond(config.minimumThroughputInBps()); int seconds = NumericUtils.saturatedCast(config.minimumThroughputTimeout().getSeconds()); httpMonitoringOptions.setAllowableThroughputFailureIntervalSeconds(seconds); return Optional.of(httpMonitoringOptions); } }
1,644
0
Create_ds/aws-sdk-java-v2/core/crt-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/crt-core/src/main/java/software/amazon/awssdk/crtcore/CrtConnectionHealthConfiguration.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.crtcore; import java.time.Duration; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.utils.Validate; /** * The base class for CRT connection health configuration */ @SdkPublicApi public abstract class CrtConnectionHealthConfiguration { private final long minimumThroughputInBps; private final Duration minimumThroughputTimeout; protected CrtConnectionHealthConfiguration(DefaultBuilder<?> builder) { this.minimumThroughputInBps = Validate.paramNotNull(builder.minimumThroughputInBps, "minimumThroughputInBps"); this.minimumThroughputTimeout = Validate.isPositive(builder.minimumThroughputTimeout, "minimumThroughputTimeout"); } /** * @return the minimum amount of throughput, in bytes per second, for a connection to be considered healthy. */ public final long minimumThroughputInBps() { return minimumThroughputInBps; } /** * @return How long a connection is allowed to be unhealthy before getting shut down. */ public final Duration minimumThroughputTimeout() { return minimumThroughputTimeout; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CrtConnectionHealthConfiguration that = (CrtConnectionHealthConfiguration) o; if (minimumThroughputInBps != that.minimumThroughputInBps) { return false; } return minimumThroughputTimeout.equals(that.minimumThroughputTimeout); } @Override public int hashCode() { int result = (int) (minimumThroughputInBps ^ (minimumThroughputInBps >>> 32)); result = 31 * result + minimumThroughputTimeout.hashCode(); return result; } /** * A builder for {@link CrtConnectionHealthConfiguration}. * * <p>All implementations of this interface are mutable and not thread safe.</p> */ public interface Builder { /** * Sets a throughput threshold for connections. Throughput below this value will be considered unhealthy. * * @param minimumThroughputInBps minimum amount of throughput, in bytes per second, for a connection to be * considered healthy. * @return Builder */ Builder minimumThroughputInBps(Long minimumThroughputInBps); /** * Sets how long a connection is allowed to be unhealthy before getting shut down. * * <p> * It only supports seconds precision * * @param minimumThroughputTimeout How long a connection is allowed to be unhealthy * before getting shut down. * @return Builder */ Builder minimumThroughputTimeout(Duration minimumThroughputTimeout); CrtConnectionHealthConfiguration build(); } protected abstract static class DefaultBuilder<B extends Builder> implements Builder { private Long minimumThroughputInBps; private Duration minimumThroughputTimeout; protected DefaultBuilder() { } protected DefaultBuilder(CrtConnectionHealthConfiguration configuration) { this.minimumThroughputInBps = configuration.minimumThroughputInBps; this.minimumThroughputTimeout = configuration.minimumThroughputTimeout; } @Override public B minimumThroughputInBps(Long minimumThroughputInBps) { this.minimumThroughputInBps = minimumThroughputInBps; return (B) this; } @Override public B minimumThroughputTimeout(Duration minimumThroughputTimeout) { this.minimumThroughputTimeout = minimumThroughputTimeout; return (B) this; } } }
1,645
0
Create_ds/aws-sdk-java-v2/core/crt-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/crt-core/src/main/java/software/amazon/awssdk/crtcore/CrtProxyConfiguration.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.crtcore; import static software.amazon.awssdk.utils.ProxyConfigProvider.fromSystemEnvironmentSettings; import java.util.Objects; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.utils.ProxyConfigProvider; import software.amazon.awssdk.utils.ProxySystemSetting; import software.amazon.awssdk.utils.StringUtils; /** * The base class for AWS CRT proxy configuration */ @SdkPublicApi public abstract class CrtProxyConfiguration { private final String scheme; private final String host; private final int port; private final String username; private final String password; private final Boolean useSystemPropertyValues; private final Boolean useEnvironmentVariableValues; protected CrtProxyConfiguration(DefaultBuilder<?> builder) { this.useSystemPropertyValues = builder.useSystemPropertyValues; this.useEnvironmentVariableValues = builder.useEnvironmentVariableValues; this.scheme = builder.scheme; ProxyConfigProvider proxyConfigProvider = fromSystemEnvironmentSettings(builder.useSystemPropertyValues, builder.useEnvironmentVariableValues , builder.scheme); this.host = resolveHost(builder, proxyConfigProvider); this.port = resolvePort(builder, proxyConfigProvider); this.username = resolveUsername(builder, proxyConfigProvider); this.password = resolvePassword(builder, proxyConfigProvider); } private static String resolvePassword(DefaultBuilder<?> builder, ProxyConfigProvider proxyConfigProvider) { if (!StringUtils.isEmpty(builder.password) || proxyConfigProvider == null) { return builder.password; } else { return proxyConfigProvider.password().orElseGet(() -> builder.password); } } private static String resolveUsername(DefaultBuilder<?> builder, ProxyConfigProvider proxyConfigProvider) { if (!StringUtils.isEmpty(builder.username) || proxyConfigProvider == null) { return builder.username; } else { return proxyConfigProvider.userName().orElseGet(() -> builder.username); } } private static int resolvePort(DefaultBuilder<?> builder, ProxyConfigProvider proxyConfigProvider) { if (builder.port != 0 || proxyConfigProvider == null) { return builder.port; } else { return proxyConfigProvider.port(); } } private static String resolveHost(DefaultBuilder<?> builder, ProxyConfigProvider proxyConfigProvider) { if (builder.host != null || proxyConfigProvider == null) { return builder.host; } else { return proxyConfigProvider.host(); } } /** * @return The proxy scheme. */ public final String scheme() { return scheme; } /** * @return The proxy host from the configuration if set, else from the "https.proxyHost" or "http.proxyHost" system property, * based on the scheme used, if {@link Builder#useSystemPropertyValues(Boolean)} is set to true */ public final String host() { return host; } /** * @return The proxy port from the configuration if set, else from the "https.proxyPort" or "http.proxyPort" system property, * based on the scheme used, if {@link Builder#useSystemPropertyValues(Boolean)} is set to true */ public final int port() { return port; } /** * @return The proxy username from the configuration if set, else from the "https.proxyUser" or "http.proxyUser" system * property, based on the scheme used, if {@link Builder#useSystemPropertyValues(Boolean)} is set to true * */ public final String username() { return username; } /** * @return The proxy password from the configuration if set, else from the "https.proxyPassword" or "http.proxyPassword" * system property, based on the scheme used, if {@link Builder#useSystemPropertyValues(Boolean)} is set * to true * */ public final String password() { return password; } /** * Indicates whether environment variables are utilized for proxy configuration. * * @return {@code true} if environment variables are being used for proxy configuration, {@code false} otherwise. */ public final Boolean isUseEnvironmentVariableValues() { return useEnvironmentVariableValues; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CrtProxyConfiguration that = (CrtProxyConfiguration) o; if (port != that.port) { return false; } if (!Objects.equals(scheme, that.scheme)) { return false; } if (!Objects.equals(host, that.host)) { return false; } if (!Objects.equals(username, that.username)) { return false; } if (!Objects.equals(password, that.password)) { return false; } if (!Objects.equals(useSystemPropertyValues, that.useSystemPropertyValues)) { return false; } return Objects.equals(useEnvironmentVariableValues, that.useEnvironmentVariableValues); } @Override public int hashCode() { int result = scheme != null ? scheme.hashCode() : 0; result = 31 * result + (host != null ? host.hashCode() : 0); result = 31 * result + port; result = 31 * result + (username != null ? username.hashCode() : 0); result = 31 * result + (password != null ? password.hashCode() : 0); result = 31 * result + (useSystemPropertyValues != null ? useSystemPropertyValues.hashCode() : 0); result = 31 * result + (useEnvironmentVariableValues != null ? useEnvironmentVariableValues.hashCode() : 0); result = 31 * result + (scheme != null ? scheme.hashCode() : 0); return result; } /** * Builder for {@link CrtProxyConfiguration}. */ public interface Builder { /** * Set the hostname of the proxy. * @param host The proxy host. * @return This object for method chaining. */ Builder host(String host); /** * Set the port that the proxy expects connections on. * @param port The proxy port. * @return This object for method chaining. */ Builder port(int port); /** * The HTTP scheme to use for connecting to the proxy. Valid values are {@code http} and {@code https}. * <p> * The client defaults to {@code http} if none is given. * * @param scheme The proxy scheme. * @return This object for method chaining. */ Builder scheme(String scheme); /** * The username to use for basic proxy authentication * <p> * If not set, the client will not use basic authentication * * @param username The basic authentication username. * @return This object for method chaining. */ Builder username(String username); /** * The password to use for basic proxy authentication * <p> * If not set, the client will not use basic authentication * * @param password The basic authentication password. * @return This object for method chaining. */ Builder password(String password); /** * The option whether to use system property values from {@link ProxySystemSetting} if any of the config options are * missing. The value is set to "true" by default which means SDK will automatically use system property values if options * are not provided during building the {@link CrtProxyConfiguration} object. To disable this behaviour, set this value to * false.It is important to note that when this property is set to "true," all proxy settings will exclusively originate * from system properties, and no partial settings will be obtained from EnvironmentVariableValues. * * @param useSystemPropertyValues The option whether to use system property values * @return This object for method chaining. */ Builder useSystemPropertyValues(Boolean useSystemPropertyValues); /** * The option whether to use environment variable values from {@link ProxySystemSetting} if any of the config options are * missing. The value is set to "true" by default which means SDK will automatically use environment variable values if * options are not provided during building the {@link CrtProxyConfiguration} object. To disable this behavior, set this * value to false.It is important to note that when this property is set to "true," all proxy settings will exclusively * originate from environment variableValues, and no partial settings will be obtained from SystemPropertyValues. * * @param useEnvironmentVariableValues The option whether to use environment variable values * @return This object for method chaining. */ Builder useEnvironmentVariableValues(Boolean useEnvironmentVariableValues); CrtProxyConfiguration build(); } protected abstract static class DefaultBuilder<B extends Builder> implements Builder { private String scheme; private String host; private int port = 0; private String username; private String password; private Boolean useSystemPropertyValues = Boolean.TRUE; private Boolean useEnvironmentVariableValues = Boolean.TRUE; protected DefaultBuilder() { } protected DefaultBuilder(CrtProxyConfiguration proxyConfiguration) { this.useSystemPropertyValues = proxyConfiguration.useSystemPropertyValues; this.useEnvironmentVariableValues = proxyConfiguration.useEnvironmentVariableValues; this.scheme = proxyConfiguration.scheme; this.host = proxyConfiguration.host; this.port = proxyConfiguration.port; this.username = proxyConfiguration.username; this.password = proxyConfiguration.password; } @Override public B scheme(String scheme) { this.scheme = scheme; return (B) this; } @Override public B host(String host) { this.host = host; return (B) this; } @Override public B port(int port) { this.port = port; return (B) this; } @Override public B username(String username) { this.username = username; return (B) this; } @Override public B password(String password) { this.password = password; return (B) this; } @Override public B useSystemPropertyValues(Boolean useSystemPropertyValues) { this.useSystemPropertyValues = useSystemPropertyValues; return (B) this; } @Override public B useEnvironmentVariableValues(Boolean useEnvironmentVariableValues) { this.useEnvironmentVariableValues = useEnvironmentVariableValues; return (B) this; } public B setuseEnvironmentVariableValues(Boolean useEnvironmentVariableValues) { return useEnvironmentVariableValues(useEnvironmentVariableValues); } public void setUseSystemPropertyValues(Boolean useSystemPropertyValues) { useSystemPropertyValues(useSystemPropertyValues); } } }
1,646
0
Create_ds/aws-sdk-java-v2/core/checksums-spi/src/main/java/software/amazon/awssdk/checksums
Create_ds/aws-sdk-java-v2/core/checksums-spi/src/main/java/software/amazon/awssdk/checksums/spi/ChecksumAlgorithm.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.checksums.spi; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * An interface for declaring the implementation of a checksum. */ @SdkProtectedApi public interface ChecksumAlgorithm { /** * The ID of the checksum algorithm. This is matched against algorithm * names used in smithy traits * (e.g. "CRC32C" from the aws.protocols#HTTPChecksum smithy trait) */ String algorithmId(); }
1,647
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/token/TestBearerToken.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.token; import java.time.Instant; import java.util.Optional; import software.amazon.awssdk.auth.token.credentials.SdkToken; public class TestBearerToken implements SdkToken { private String token; private Instant expirationTime; @Override public String token() { return token; } @Override public Optional<Instant> expirationTime() { return Optional.ofNullable(expirationTime); } private TestBearerToken(String token, Instant expirationTime) { this.token = token; this.expirationTime = expirationTime; } public static TestBearerToken create(String token, Instant expirationTime){ return new TestBearerToken(token, expirationTime); } public static TestBearerToken create(String token){ return new TestBearerToken(token, null); } }
1,648
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/token
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/token/signer/SdkTokenExecutionAttributeTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.token.signer; import static org.assertj.core.api.Assertions.assertThat; import java.util.concurrent.CompletableFuture; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import software.amazon.awssdk.auth.token.credentials.SdkToken; import software.amazon.awssdk.core.SelectedAuthScheme; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute; import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeOption; import software.amazon.awssdk.http.auth.spi.signer.HttpSigner; import software.amazon.awssdk.identity.spi.Identity; class SdkTokenExecutionAttributeTest { private static final SelectedAuthScheme<Identity> EMPTY_SELECTED_AUTH_SCHEME = new SelectedAuthScheme<>(CompletableFuture.completedFuture(Mockito.mock(Identity.class)), (HttpSigner<Identity>) Mockito.mock(HttpSigner.class), AuthSchemeOption.builder().schemeId("mock").build()); private ExecutionAttributes attributes; @BeforeEach public void setup() { this.attributes = new ExecutionAttributes(); } @Test public void awsCredentials_oldAndNewAttributeAreMirrored() { SdkToken token = Mockito.mock(SdkToken.class); // If selected auth scheme is null, writing non-null old property can be read with new property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, null); attributes.putAttribute(SdkTokenExecutionAttribute.SDK_TOKEN, token); assertThat(attributes.getAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME).identity().join()).isSameAs(token); // If selected auth scheme is null, writing null to old property can be read with new property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, null); attributes.putAttribute(SdkTokenExecutionAttribute.SDK_TOKEN, null); assertThat(attributes.getAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME).identity().join()).isNull(); // If selected auth scheme is non-null, writing non-null to old property can be read with new property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, EMPTY_SELECTED_AUTH_SCHEME); attributes.putAttribute(SdkTokenExecutionAttribute.SDK_TOKEN, token); assertThat(attributes.getAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME).identity().join()).isSameAs(token); // If selected auth scheme is non-null, writing null to old property can be read with new property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, EMPTY_SELECTED_AUTH_SCHEME); attributes.putAttribute(SdkTokenExecutionAttribute.SDK_TOKEN, null); assertThat(attributes.getAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME).identity().join()).isNull(); // Writing non-null new property can be read with old property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, new SelectedAuthScheme<>(CompletableFuture.completedFuture(token), EMPTY_SELECTED_AUTH_SCHEME.signer(), EMPTY_SELECTED_AUTH_SCHEME.authSchemeOption())); assertThat(attributes.getAttribute(SdkTokenExecutionAttribute.SDK_TOKEN)).isSameAs(token); // Writing null new property can be read with old property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, new SelectedAuthScheme<>(CompletableFuture.completedFuture(null), EMPTY_SELECTED_AUTH_SCHEME.signer(), EMPTY_SELECTED_AUTH_SCHEME.authSchemeOption())); assertThat(attributes.getAttribute(SdkTokenExecutionAttribute.SDK_TOKEN)).isNull(); // Null selected auth scheme can be read with old property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, null); assertThat(attributes.getAttribute(SdkTokenExecutionAttribute.SDK_TOKEN)).isNull(); } }
1,649
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/token
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/token/internal/LazyTokenProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.token.internal; import java.util.function.Supplier; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import software.amazon.awssdk.auth.token.credentials.SdkTokenProvider; import software.amazon.awssdk.utils.SdkAutoCloseable; public class LazyTokenProviderTest { @SuppressWarnings("unchecked") private final Supplier<SdkTokenProvider> credentialsConstructor = Mockito.mock(Supplier.class); private final SdkTokenProvider credentials = Mockito.mock(SdkTokenProvider.class); @BeforeEach public void reset() { Mockito.reset(credentials, credentialsConstructor); Mockito.when(credentialsConstructor.get()).thenReturn(credentials); } @Test public void creationDoesntInvokeSupplier() { LazyTokenProvider.create(credentialsConstructor); Mockito.verifyNoMoreInteractions(credentialsConstructor); } @Test public void resolveCredentialsInvokesSupplierExactlyOnce() { LazyTokenProvider credentialsProvider = LazyTokenProvider.create(credentialsConstructor); credentialsProvider.resolveToken(); credentialsProvider.resolveToken(); Mockito.verify(credentialsConstructor).get(); Mockito.verify(credentials, Mockito.times(2)).resolveToken(); } @Test public void delegatesClosesInitializerAndValue() { CloseableSupplier initializer = Mockito.mock(CloseableSupplier.class); CloseableCredentialsProvider value = Mockito.mock(CloseableCredentialsProvider.class); Mockito.when(initializer.get()).thenReturn(value); LazyTokenProvider.create(initializer).close(); Mockito.verify(initializer).close(); Mockito.verify(value).close(); } @Test public void delegatesClosesInitializerEvenIfGetFails() { CloseableSupplier initializer = Mockito.mock(CloseableSupplier.class); Mockito.when(initializer.get()).thenThrow(new RuntimeException()); LazyTokenProvider.create(initializer).close(); Mockito.verify(initializer).close(); } private interface CloseableSupplier extends Supplier<SdkTokenProvider>, SdkAutoCloseable {} private interface CloseableCredentialsProvider extends SdkAutoCloseable, SdkTokenProvider {} }
1,650
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/token
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/token/credentials/ProfileTokenProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.token.credentials; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.function.Supplier; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.utils.StringInputStream; class ProfileTokenProviderTest { @Test void missingProfileFile_throwsException() { ProfileTokenProvider provider = new ProfileTokenProvider.BuilderImpl() .defaultProfileFileLoader(() -> ProfileFile.builder() .content(new StringInputStream("")) .type(ProfileFile.Type.CONFIGURATION) .build()) .build(); assertThatThrownBy(provider::resolveToken).isInstanceOf(SdkClientException.class); } @Test void emptyProfileFile_throwsException() { ProfileTokenProvider provider = new ProfileTokenProvider.BuilderImpl() .defaultProfileFileLoader(() -> ProfileFile.builder() .content(new StringInputStream("")) .type(ProfileFile.Type.CONFIGURATION) .build()) .build(); assertThatThrownBy(provider::resolveToken).isInstanceOf(SdkClientException.class); } @Test void missingProfile_throwsException() { ProfileFile file = profileFile("[default]\n" + "aws_access_key_id = defaultAccessKey\n" + "aws_secret_access_key = defaultSecretAccessKey"); ProfileTokenProvider provider = ProfileTokenProvider.builder().profileFile(() -> file).profileName("sso").build(); assertThatThrownBy(provider::resolveToken).isInstanceOf(SdkClientException.class); } @Test void compatibleProfileSettings_callsLoader() { ProfileFile file = profileFile("[default]"); ProfileTokenProvider provider = ProfileTokenProvider.builder().profileFile(() -> file).profileName("default").build(); assertThatThrownBy(provider::resolveToken).hasMessageContaining("does not have sso_session property"); } @Test void resolveToken_profileFileSupplier_suppliesObjectPerCall() { ProfileFile file1 = profileFile("[profile sso]\n" + "aws_access_key_id = defaultAccessKey\n" + "aws_secret_access_key = defaultSecretAccessKey\n" + "sso_session = xyz"); ProfileFile file2 = profileFile("[profile sso]\n" + "aws_access_key_id = modifiedAccessKey\n" + "aws_secret_access_key = modifiedSecretAccessKey\n" + "sso_session = xyz"); Supplier<ProfileFile> supplier = Mockito.mock(Supplier.class); ProfileTokenProvider provider = ProfileTokenProvider.builder().profileFile(supplier).profileName("sso").build(); Mockito.when(supplier.get()).thenReturn(file1, file2); assertThatThrownBy(provider::resolveToken).isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(provider::resolveToken).isInstanceOf(IllegalArgumentException.class); Mockito.verify(supplier, Mockito.times(2)).get(); } private ProfileFile profileFile(String string) { return ProfileFile.builder() .content(new StringInputStream(string)) .type(ProfileFile.Type.CONFIGURATION) .build(); } }
1,651
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/token
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/token/credentials/SdkTokenProviderChainTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.token.credentials; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.time.Instant; import java.util.Arrays; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.Executable; import software.amazon.awssdk.auth.token.TestBearerToken; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.identity.spi.TokenIdentity; public class SdkTokenProviderChainTest { public static final Instant SAMPLE_EXPIRATION_TIME = Instant.ofEpochMilli(1642108606L); public static final String SAMPLE_TOKEN_STRING = "mJ_9.B5f-4.1Jmv"; /** * Tests that, by default, the chain remembers which provider was able to provide token, and only calls that provider * for any additional calls to getToken. */ @Test public void resolveToken_reuseEnabled_reusesLastProvider() { MockTokenProvider provider1 = new MockTokenProvider("Failed!"); MockTokenProvider provider2 = new MockTokenProvider(); SdkTokenProviderChain chain = SdkTokenProviderChain.builder() .tokenProviders(provider1, provider2) .build(); assertEquals(0, provider1.getTokenCallCount); assertEquals(0, provider2.getTokenCallCount); chain.resolveToken(); assertEquals(1, provider1.getTokenCallCount); assertEquals(1, provider2.getTokenCallCount); chain.resolveToken(); assertEquals(1, provider1.getTokenCallCount); assertEquals(2, provider2.getTokenCallCount); chain.resolveToken(); assertEquals(1, provider1.getTokenCallCount); assertEquals(3, provider2.getTokenCallCount); } /** * Tests that, when provider caching is disabled, the chain will always try all providers in the chain, starting with the * first, until it finds a provider that can return token. */ @Test public void resolveToken_reuseDisabled_alwaysGoesThroughChain() { MockTokenProvider provider1 = new MockTokenProvider("Failed!"); MockTokenProvider provider2 = new MockTokenProvider(); SdkTokenProviderChain chain = SdkTokenProviderChain.builder() .tokenProviders(provider1, provider2) .reuseLastProviderEnabled(false) .build(); assertEquals(0, provider1.getTokenCallCount); assertEquals(0, provider2.getTokenCallCount); chain.resolveToken(); assertEquals(1, provider1.getTokenCallCount); assertEquals(1, provider2.getTokenCallCount); chain.resolveToken(); assertEquals(2, provider1.getTokenCallCount); assertEquals(2, provider2.getTokenCallCount); } /** * Tests that getToken throws an Exception if all providers in the chain fail to provide token. */ @Test public void resolveToken_allProvidersFail_throwsExceptionWithMessageFromAllProviders() { MockTokenProvider provider1 = new MockTokenProvider("Failed!"); MockTokenProvider provider2 = new MockTokenProvider("Bad!"); SdkTokenProviderChain chain = SdkTokenProviderChain.builder() .tokenProviders(provider1, provider2) .build(); SdkClientException e = assertThrows(SdkClientException.class, () -> chain.resolveToken()); assertThat(e.getMessage()).contains(provider1.exceptionMessage); assertThat(e.getMessage()).contains(provider2.exceptionMessage); } @Test public void resolveToken_emptyChain_throwsException() { assertThrowsIllegalArgument(() -> SdkTokenProviderChain.of()); assertThrowsIllegalArgument(() -> SdkTokenProviderChain .builder() .tokenProviders() .build()); assertThrowsIllegalArgument(() -> SdkTokenProviderChain .builder() .tokenProviders(Arrays.asList()) .build()); } private void assertThrowsIllegalArgument(Executable executable) { IllegalArgumentException e = assertThrows(IllegalArgumentException.class, executable); assertThat(e.getMessage()).contains("No token providers were specified."); } /** * Tests that the chain is setup correctly with the overloaded methods that accept the AwsCredentialsProvider type. */ @Test public void createMethods_withOldTokenType_work() { SdkTokenProvider provider = new MockTokenProvider(); assertChainResolvesCorrectly(SdkTokenProviderChain.of(provider)); assertChainResolvesCorrectly(SdkTokenProviderChain.builder().tokenProviders(provider).build()); assertChainResolvesCorrectly(SdkTokenProviderChain.builder().tokenProviders(Arrays.asList(provider)).build()); assertChainResolvesCorrectly(SdkTokenProviderChain.builder().addTokenProvider(provider).build()); } /** * Tests that the chain is setup correctly with the overloaded methods that accept the IdentityProvider type. */ @Test public void createMethods_withNewTokenType_work() { IdentityProvider<TokenIdentity> provider = new MockTokenProvider(); assertChainResolvesCorrectly(SdkTokenProviderChain.of(provider)); assertChainResolvesCorrectly(SdkTokenProviderChain.builder().tokenProviders(provider).build()); assertChainResolvesCorrectly(SdkTokenProviderChain.builder().tokenIdentityProviders(Arrays.asList(provider)).build()); assertChainResolvesCorrectly(SdkTokenProviderChain.builder().addTokenProvider(provider).build()); } private static void assertChainResolvesCorrectly(SdkTokenProviderChain chain) { SdkToken token = chain.resolveToken(); assertThat(token.token()).isEqualTo(SAMPLE_TOKEN_STRING); } private static final class MockTokenProvider implements SdkTokenProvider { private final SdkTokenProvider sdkTokenProvider; private final String exceptionMessage; int getTokenCallCount = 0; private MockTokenProvider() { this(null); } private MockTokenProvider(String exceptionMessage) { sdkTokenProvider = StaticTokenProvider.create(TestBearerToken.create(SAMPLE_TOKEN_STRING, SAMPLE_EXPIRATION_TIME)); this.exceptionMessage = exceptionMessage; } @Override public SdkToken resolveToken() { getTokenCallCount++; if (exceptionMessage != null) { throw new RuntimeException(exceptionMessage); } else { return sdkTokenProvider.resolveToken(); } } } }
1,652
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/token/credentials
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/token/credentials/internal/TokenUtilsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.token.credentials.internal; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.credentials.TokenUtils; import software.amazon.awssdk.auth.token.TestBearerToken; import software.amazon.awssdk.auth.token.credentials.SdkToken; import software.amazon.awssdk.identity.spi.TokenIdentity; public class TokenUtilsTest { @Test public void toSdkToken_null_returnsNull() { assertThat(TokenUtils.toSdkToken(null)).isNull(); } @Test public void toSdkToken_SdkToken_returnsAsIs() { TokenIdentity input = TestBearerToken.create("t"); SdkToken output = TokenUtils.toSdkToken(input); assertThat(output).isSameAs(input); } @Test public void toSdkToken_TokenIdentity_returnsSdkToken() { TokenIdentity tokenIdentity = TokenIdentity.create("token"); SdkToken sdkToken = TokenUtils.toSdkToken(tokenIdentity); assertThat(sdkToken.token()).isEqualTo("token"); } }
1,653
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/token/credentials
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/token/credentials/aws/DefaultAwsTokenProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.token.credentials.aws; import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.token.credentials.aws.DefaultAwsTokenProvider; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.utils.StringInputStream; public class DefaultAwsTokenProviderTest { @Test public void defaultCreate() { DefaultAwsTokenProvider tokenProvider = DefaultAwsTokenProvider.create(); assertThatThrownBy(tokenProvider::resolveToken) .isInstanceOf(SdkClientException.class) .hasMessageContaining("Unable to load token"); } @Test public void profileFile() { DefaultAwsTokenProvider tokenProvider = DefaultAwsTokenProvider.builder() .profileFile(() -> profileFile("[default]")) .profileName("default") .build(); assertThatThrownBy(tokenProvider::resolveToken) .isInstanceOf(SdkClientException.class) .hasMessageContaining("Unable to load token"); } private ProfileFile profileFile(String string) { return ProfileFile.builder() .content(new StringInputStream(string)) .type(ProfileFile.Type.CONFIGURATION) .build(); } }
1,654
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer/S3SignerExecutionAttributeTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.signer; import static org.assertj.core.api.Assertions.assertThat; import java.util.concurrent.CompletableFuture; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import software.amazon.awssdk.core.SelectedAuthScheme; import software.amazon.awssdk.core.interceptor.ExecutionAttribute; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute; import software.amazon.awssdk.http.auth.aws.signer.AwsV4FamilyHttpSigner; import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeOption; import software.amazon.awssdk.http.auth.spi.signer.HttpSigner; import software.amazon.awssdk.http.auth.spi.signer.SignerProperty; import software.amazon.awssdk.identity.spi.Identity; class S3SignerExecutionAttributeTest { private static final SelectedAuthScheme<Identity> EMPTY_SELECTED_AUTH_SCHEME = new SelectedAuthScheme<>(CompletableFuture.completedFuture(Mockito.mock(Identity.class)), (HttpSigner<Identity>) Mockito.mock(HttpSigner.class), AuthSchemeOption.builder().schemeId("mock").build()); private ExecutionAttributes attributes; @BeforeEach public void setup() { this.attributes = new ExecutionAttributes(); } @Test public void enableChunkedEncoding_oldAndNewAttributeAreMirrored() { assertOldAndNewBooleanAttributesAreMirrored(S3SignerExecutionAttribute.ENABLE_CHUNKED_ENCODING, AwsV4FamilyHttpSigner.CHUNK_ENCODING_ENABLED); } @Test public void enablePayloadSigning_oldAndNewAttributeAreMirrored() { assertOldAndNewBooleanAttributesAreMirrored(S3SignerExecutionAttribute.ENABLE_PAYLOAD_SIGNING, AwsV4FamilyHttpSigner.PAYLOAD_SIGNING_ENABLED); } private void assertOldAndNewBooleanAttributesAreMirrored(ExecutionAttribute<Boolean> attribute, SignerProperty<Boolean> property) { assertOldAndNewAttributesAreMirrored(attribute, property, true, true); assertOldAndNewAttributesAreMirrored(attribute, property, false, false); } private <T, U> void assertOldAndNewAttributesAreMirrored(ExecutionAttribute<T> oldAttribute, SignerProperty<U> newProperty, T oldPropertyValue, U newPropertyValue) { // If selected auth scheme is null, writing non-null old property can be read with new property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, null); assertOldAttributeWrite_canBeReadFromNewAttribute(oldAttribute, newProperty, oldPropertyValue, newPropertyValue); // If selected auth scheme is null, writing null to old property can be read with new property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, null); assertOldAttributeWrite_canBeReadFromNewAttribute(oldAttribute, newProperty, null, null); // If selected auth scheme is non-null, writing non-null to old property can be read with new property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, EMPTY_SELECTED_AUTH_SCHEME); assertOldAttributeWrite_canBeReadFromNewAttribute(oldAttribute, newProperty, oldPropertyValue, newPropertyValue); // If selected auth scheme is non-null, writing null to old property can be read with new property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, EMPTY_SELECTED_AUTH_SCHEME); assertOldAttributeWrite_canBeReadFromNewAttribute(oldAttribute, newProperty, null, null); // Writing non-null new property can be read with old property assertNewPropertyWrite_canBeReadFromNewAttribute(oldAttribute, newProperty, oldPropertyValue, newPropertyValue); // Writing null new property can be read with old property assertNewPropertyWrite_canBeReadFromNewAttribute(oldAttribute, newProperty, null, null); // Null selected auth scheme can be read with old property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, null); assertThat(attributes.getAttribute(oldAttribute)).isNull(); } private <T, U> void assertNewPropertyWrite_canBeReadFromNewAttribute(ExecutionAttribute<T> oldAttribute, SignerProperty<U> newProperty, T oldPropertyValue, U newPropertyValue) { AuthSchemeOption newOption = EMPTY_SELECTED_AUTH_SCHEME.authSchemeOption().copy(o -> o.putSignerProperty(newProperty, newPropertyValue)); attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, new SelectedAuthScheme<>(EMPTY_SELECTED_AUTH_SCHEME.identity(), EMPTY_SELECTED_AUTH_SCHEME.signer(), newOption)); assertThat(attributes.getAttribute(oldAttribute)).isEqualTo(oldPropertyValue); } private <T, U> void assertOldAttributeWrite_canBeReadFromNewAttribute(ExecutionAttribute<T> attributeToWrite, SignerProperty<U> propertyToRead, T valueToWrite, U propertyToExpect) { attributes.putAttribute(attributeToWrite, valueToWrite); assertThat(attributes.getAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME) .authSchemeOption() .signerProperty(propertyToRead)).isEqualTo(propertyToExpect); } }
1,655
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer/BearerTokenSignerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.signer; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.io.ByteArrayInputStream; import java.net.URI; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.token.signer.SdkTokenExecutionAttribute; import software.amazon.awssdk.auth.token.TestBearerToken; import software.amazon.awssdk.auth.signer.params.TokenSignerParams; import software.amazon.awssdk.auth.token.signer.aws.BearerTokenSigner; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; class BearerTokenSignerTest { private static final String BEARER_AUTH_MARKER = "Bearer "; @Test public void whenTokenExists_requestIsSignedCorrectly() { String tokenValue = "mF_9.B5f-4.1JqM"; BearerTokenSigner tokenSigner = BearerTokenSigner.create(); SdkHttpFullRequest signedRequest = tokenSigner.sign(generateBasicRequest(), executionAttributes(TestBearerToken.create(tokenValue))); String expectedHeader = createExpectedHeader(tokenValue); assertThat(signedRequest.firstMatchingHeader("Authorization")).hasValue(expectedHeader); } @Test public void whenTokenIsMissing_exceptionIsThrown() { BearerTokenSigner tokenSigner = BearerTokenSigner.create(); assertThatThrownBy(() -> tokenSigner.sign(generateBasicRequest(), executionAttributes(null))) .isInstanceOf(NullPointerException.class) .hasMessageContaining("token"); } @Test public void usingParamMethod_worksCorrectly() { String tokenValue = "mF_9.B5f-4.1JqM"; BearerTokenSigner tokenSigner = BearerTokenSigner.create(); SdkHttpFullRequest signedRequest = tokenSigner.sign(generateBasicRequest(), TokenSignerParams.builder() .token(TestBearerToken.create(tokenValue)) .build()); String expectedHeader = createExpectedHeader(tokenValue); assertThat(signedRequest.firstMatchingHeader("Authorization")).hasValue(expectedHeader); } private static String createExpectedHeader(String token) { return BEARER_AUTH_MARKER + token; } private static ExecutionAttributes executionAttributes(TestBearerToken token) { ExecutionAttributes executionAttributes = new ExecutionAttributes(); executionAttributes.putAttribute(SdkTokenExecutionAttribute.SDK_TOKEN, token); return executionAttributes; } private static SdkHttpFullRequest generateBasicRequest() { return SdkHttpFullRequest.builder() .contentStreamProvider(() -> new ByteArrayInputStream("{\"TableName\": \"foo\"}".getBytes())) .method(SdkHttpMethod.POST) .putHeader("Host", "demo.us-east-1.amazonaws.com") .putHeader("x-amz-archive-description", "test test") .encodedPath("/") .uri(URI.create("http://demo.us-east-1.amazonaws.com")) .build(); } }
1,656
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer/NonStreamingAsyncBodyAws4SignerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.signer; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import io.reactivex.Flowable; import java.io.ByteArrayInputStream; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.time.Clock; import java.time.Instant; import java.time.ZoneId; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; import org.junit.jupiter.api.Test; import org.mockito.stubbing.Answer; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentials; import software.amazon.awssdk.auth.signer.params.SignerChecksumParams; import software.amazon.awssdk.auth.signer.params.Aws4SignerParams; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.checksums.Algorithm; import software.amazon.awssdk.http.ContentStreamProvider; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.regions.Region; public class NonStreamingAsyncBodyAws4SignerTest { @Test void test_sign_computesCorrectSignature() { Aws4Signer aws4Signer = Aws4Signer.create(); AsyncAws4Signer asyncAws4Signer = AsyncAws4Signer.create(); byte[] content = "Hello AWS!".getBytes(StandardCharsets.UTF_8); ContentStreamProvider syncBody = () -> new ByteArrayInputStream(content); AsyncRequestBody asyncBody = AsyncRequestBody.fromBytes(content); SdkHttpFullRequest httpRequest = SdkHttpFullRequest.builder() .protocol("https") .host("my-cool-aws-service.us-west-2.amazonaws.com") .method(SdkHttpMethod.GET) .putHeader("header1", "headerval1") .contentStreamProvider(syncBody) .build(); AwsCredentials credentials = AwsBasicCredentials.create("akid", "skid"); Aws4SignerParams signerParams = Aws4SignerParams.builder() .awsCredentials(credentials) .signingClockOverride(Clock.fixed(Instant.EPOCH, ZoneId.of("UTC"))) .signingName("my-cool-aws-service") .signingRegion(Region.US_WEST_2) .build(); List<String> syncSignature = aws4Signer.sign(httpRequest, signerParams).headers().get("Authorization"); List<String> asyncSignature = asyncAws4Signer.signWithBody(httpRequest, asyncBody, signerParams).join() .headers().get("Authorization"); assertThat(asyncSignature).isEqualTo(syncSignature); } @Test void test_sign_publisherThrows_exceptionPropagated() { AsyncAws4Signer asyncAws4Signer = AsyncAws4Signer.create(); RuntimeException error = new RuntimeException("error"); Flowable<ByteBuffer> errorPublisher = Flowable.error(error); AsyncRequestBody asyncBody = new AsyncRequestBody() { @Override public Optional<Long> contentLength() { return Optional.of(42L); } @Override public void subscribe(Subscriber<? super ByteBuffer> subscriber) { errorPublisher.subscribe(subscriber); } }; SdkHttpFullRequest httpRequest = SdkHttpFullRequest.builder() .protocol("https") .host("my-cool-aws-service.us-west-2.amazonaws.com") .method(SdkHttpMethod.GET) .putHeader("header1", "headerval1") .build(); AwsCredentials credentials = AwsBasicCredentials.create("akid", "skid"); Aws4SignerParams signerParams = Aws4SignerParams.builder() .awsCredentials(credentials) .signingClockOverride(Clock.fixed(Instant.EPOCH, ZoneId.of("UTC"))) .signingName("my-cool-aws-service") .signingRegion(Region.US_WEST_2) .build(); assertThatThrownBy(asyncAws4Signer.signWithBody(httpRequest, asyncBody, signerParams)::join) .hasCause(error); } @Test void test_sign_futureCancelled_propagatedToPublisher() { SdkHttpFullRequest httpRequest = SdkHttpFullRequest.builder() .protocol("https") .host("my-cool-aws-service.us-west-2.amazonaws.com") .method(SdkHttpMethod.GET) .putHeader("header1", "headerval1") .build(); AwsCredentials credentials = AwsBasicCredentials.create("akid", "skid"); Aws4SignerParams signerParams = Aws4SignerParams.builder() .awsCredentials(credentials) .signingClockOverride(Clock.fixed(Instant.EPOCH, ZoneId.of("UTC"))) .signingName("my-cool-aws-service") .signingRegion(Region.US_WEST_2) .build(); AsyncRequestBody mockRequestBody = mock(AsyncRequestBody.class); Subscription mockSubscription = mock(Subscription.class); doAnswer((Answer<Void>) invocationOnMock -> { Subscriber subscriber = invocationOnMock.getArgument(0, Subscriber.class); subscriber.onSubscribe(mockSubscription); return null; }).when(mockRequestBody).subscribe(any(Subscriber.class)); AsyncAws4Signer asyncAws4Signer = AsyncAws4Signer.create(); CompletableFuture<SdkHttpFullRequest> signedRequestFuture = asyncAws4Signer.signWithBody(httpRequest, mockRequestBody, signerParams); signedRequestFuture.cancel(true); verify(mockSubscription).cancel(); } @Test void test_sign_computesCorrectSignatureWithChecksum() { Aws4Signer aws4Signer = Aws4Signer.create(); AsyncAws4Signer asyncAws4Signer = AsyncAws4Signer.create(); byte[] content = "abc".getBytes(StandardCharsets.UTF_8); ContentStreamProvider syncBody = () -> new ByteArrayInputStream(content); AsyncRequestBody asyncBody = AsyncRequestBody.fromBytes(content); SdkHttpFullRequest httpRequest = SdkHttpFullRequest.builder() .protocol("https") .host("my-cool-aws-service.us-west-2.amazonaws.com") .method(SdkHttpMethod.GET) .putHeader("header1", "headerval1") .contentStreamProvider(syncBody) .build(); AwsCredentials credentials = AwsBasicCredentials.create("akid", "skid"); Aws4SignerParams signerParams = Aws4SignerParams.builder() .awsCredentials(credentials) .signingClockOverride(Clock.fixed(Instant.EPOCH, ZoneId.of("UTC"))) .signingName("my-cool-aws-service") .signingRegion(Region.US_WEST_2) .checksumParams(SignerChecksumParams.builder().algorithm(Algorithm.SHA256) .checksumHeaderName("x-amzn-header") .isStreamingRequest(true) .build()) .build(); List<String> syncSignature = aws4Signer.sign(httpRequest, signerParams).headers().get("Authorization"); final SdkHttpFullRequest sdkHttpFullRequest = asyncAws4Signer.signWithBody(httpRequest, asyncBody, signerParams).join(); List<String> asyncSignature = sdkHttpFullRequest.headers().get("Authorization"); assertThat(asyncSignature).isEqualTo(syncSignature); final List<String> stringList = sdkHttpFullRequest.headers().get("x-amzn-header"); assertThat(stringList.stream().findFirst()).hasValue("ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0="); assertThat(sdkHttpFullRequest.firstMatchingHeader(("x-amzn-trailer"))).isNotPresent(); } }
1,657
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer/EventStreamAws4SignerTest.java
package software.amazon.awssdk.auth.signer; import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; import io.reactivex.Flowable; import java.net.URI; import java.nio.ByteBuffer; import java.time.Clock; import java.time.Instant; import java.time.ZoneId; import java.time.ZoneOffset; import java.util.Base64; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentials; import software.amazon.awssdk.auth.signer.internal.SignerTestUtils; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.regions.Region; import software.amazon.eventstream.HeaderValue; import software.amazon.eventstream.Message; import software.amazon.eventstream.MessageDecoder; public class EventStreamAws4SignerTest { /** * Verify that when an event stream is open from one day to the next, the signature is properly signed for the day of the * event. */ @Test public void openStreamEventSignaturesCanRollOverBetweenDays() { EventStreamAws4Signer signer = EventStreamAws4Signer.create(); Region region = Region.US_WEST_2; AwsCredentials credentials = AwsBasicCredentials.create("a", "s"); String signingName = "name"; AdjustableClock clock = new AdjustableClock(); clock.time = Instant.parse("2020-01-01T23:59:59Z"); SdkHttpFullRequest initialRequest = SdkHttpFullRequest.builder() .uri(URI.create("http://localhost:8080")) .method(SdkHttpMethod.GET) .build(); SdkHttpFullRequest signedRequest = SignerTestUtils.signRequest(signer, initialRequest, credentials, signingName, clock, region.id()); ByteBuffer event = new Message(Collections.emptyMap(), "foo".getBytes(UTF_8)).toByteBuffer(); Callable<ByteBuffer> lastEvent = () -> { clock.time = Instant.parse("2020-01-02T00:00:00Z"); return event; }; AsyncRequestBody requestBody = AsyncRequestBody.fromPublisher(Flowable.concatArray(Flowable.just(event), Flowable.fromCallable(lastEvent))); AsyncRequestBody signedBody = SignerTestUtils.signAsyncRequest(signer, signedRequest, requestBody, credentials, signingName, clock, region.id()); List<Message> signedMessages = readMessages(signedBody); assertThat(signedMessages.size()).isEqualTo(3); Map<String, HeaderValue> firstMessageHeaders = signedMessages.get(0).getHeaders(); assertThat(firstMessageHeaders.get(":date").getTimestamp()).isEqualTo("2020-01-01T23:59:59Z"); assertThat(Base64.getEncoder().encodeToString(firstMessageHeaders.get(":chunk-signature").getByteArray())) .isEqualTo("EFt7ZU043r/TJE8U+1GxJXscmNxoqmIdGtUIl8wE9u0="); Map<String, HeaderValue> lastMessageHeaders = signedMessages.get(2).getHeaders(); assertThat(lastMessageHeaders.get(":date").getTimestamp()).isEqualTo("2020-01-02T00:00:00Z"); assertThat(Base64.getEncoder().encodeToString(lastMessageHeaders.get(":chunk-signature").getByteArray())) .isEqualTo("UTRGo0D7BQytiVkH1VofR/8f3uFsM4V5QR1A8grr1+M="); } private List<Message> readMessages(AsyncRequestBody signedBody) { MessageDecoder decoder = new MessageDecoder(); Flowable.fromPublisher(signedBody).blockingForEach(x -> decoder.feed(x.array())); return decoder.getDecodedMessages(); } private static class AdjustableClock extends Clock { private Instant time; @Override public ZoneId getZone() { return ZoneOffset.UTC; } @Override public Clock withZone(ZoneId zone) { throw new UnsupportedOperationException(); } @Override public Instant instant() { return time; } } }
1,658
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer/AwsS3V4SignerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.signer; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import java.net.URI; import java.nio.ByteBuffer; import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; import java.util.concurrent.ThreadLocalRandom; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.signer.params.Aws4PresignerParams; import software.amazon.awssdk.auth.signer.params.AwsS3V4SignerParams; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.regions.Region; class AwsS3V4SignerTest { private static final Clock UTC_EPOCH_CLOCK = Clock.fixed(Instant.EPOCH, ZoneOffset.UTC); @Test public void signWithParams_urlsAreNotNormalized() { byte[] bytes = new byte[1000]; ThreadLocalRandom.current().nextBytes(bytes); ByteBuffer buffer = ByteBuffer.wrap(bytes); URI target = URI.create("https://test.com/./foo"); SdkHttpFullRequest request = SdkHttpFullRequest.builder() .contentStreamProvider(RequestBody.fromByteBuffer(buffer) .contentStreamProvider()) .method(SdkHttpMethod.GET) .uri(target) .encodedPath(target.getPath()) .build(); AwsS3V4Signer signer = AwsS3V4Signer.create(); SdkHttpFullRequest signedRequest = signer.sign(request, AwsS3V4SignerParams.builder() .awsCredentials(AwsBasicCredentials.create("akid", "skid")) .signingRegion(Region.US_WEST_2) .signingName("s3") .signingClockOverride(UTC_EPOCH_CLOCK) .build()); assertThat(signedRequest.firstMatchingHeader("Authorization")) .hasValue("AWS4-HMAC-SHA256 Credential=akid/19700101/us-west-2/s3/aws4_request, " + "SignedHeaders=host;x-amz-content-sha256;x-amz-date, " + "Signature=a3b97f9de337ab254f3b366c3d0b3c67016d2d8d8ba7e0e4ddab0ccebe84992a"); } @Test public void signWithExecutionAttributes_urlsAreNotNormalized() { byte[] bytes = new byte[1000]; ThreadLocalRandom.current().nextBytes(bytes); ByteBuffer buffer = ByteBuffer.wrap(bytes); URI target = URI.create("https://test.com/./foo"); SdkHttpFullRequest request = SdkHttpFullRequest.builder() .contentStreamProvider(RequestBody.fromByteBuffer(buffer) .contentStreamProvider()) .method(SdkHttpMethod.GET) .uri(target) .encodedPath(target.getPath()) .build(); ExecutionAttributes attributes = ExecutionAttributes.builder() .put(AwsSignerExecutionAttribute.AWS_CREDENTIALS, AwsBasicCredentials.create("akid", "skid")) .put(AwsSignerExecutionAttribute.SIGNING_REGION, Region.US_WEST_2) .put(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME, "s3") .put(AwsSignerExecutionAttribute.SIGNING_CLOCK, UTC_EPOCH_CLOCK) .build(); AwsS3V4Signer signer = AwsS3V4Signer.create(); SdkHttpFullRequest signedRequest = signer.sign(request, attributes); assertThat(signedRequest.firstMatchingHeader("Authorization")) .hasValue("AWS4-HMAC-SHA256 Credential=akid/19700101/us-west-2/s3/aws4_request, " + "SignedHeaders=host;x-amz-content-sha256;x-amz-date, " + "Signature=a3b97f9de337ab254f3b366c3d0b3c67016d2d8d8ba7e0e4ddab0ccebe84992a"); } @Test public void presignWithParams_urlsAreNotNormalized() { byte[] bytes = new byte[1000]; ThreadLocalRandom.current().nextBytes(bytes); ByteBuffer buffer = ByteBuffer.wrap(bytes); URI target = URI.create("https://test.com/./foo"); SdkHttpFullRequest request = SdkHttpFullRequest.builder() .contentStreamProvider(RequestBody.fromByteBuffer(buffer) .contentStreamProvider()) .method(SdkHttpMethod.GET) .uri(target) .encodedPath(target.getPath()) .build(); AwsS3V4Signer signer = AwsS3V4Signer.create(); SdkHttpFullRequest signedRequest = signer.presign(request, Aws4PresignerParams.builder() .awsCredentials(AwsBasicCredentials.create("akid", "skid")) .signingRegion(Region.US_WEST_2) .signingName("s3") .signingClockOverride(UTC_EPOCH_CLOCK) .build()); assertThat(signedRequest.firstMatchingRawQueryParameter("X-Amz-Signature")) .hasValue("3a9d36d37e9a554b7a3803f58ee7539b5d1f52fdfe89ce6fd40fb25762a35ec3"); } @Test public void presignWithExecutionAttributes_urlsAreNotNormalized() { byte[] bytes = new byte[1000]; ThreadLocalRandom.current().nextBytes(bytes); ByteBuffer buffer = ByteBuffer.wrap(bytes); URI target = URI.create("https://test.com/./foo"); SdkHttpFullRequest request = SdkHttpFullRequest.builder() .contentStreamProvider(RequestBody.fromByteBuffer(buffer) .contentStreamProvider()) .method(SdkHttpMethod.GET) .uri(target) .encodedPath(target.getPath()) .build(); ExecutionAttributes attributes = ExecutionAttributes.builder() .put(AwsSignerExecutionAttribute.AWS_CREDENTIALS, AwsBasicCredentials.create("akid", "skid")) .put(AwsSignerExecutionAttribute.SIGNING_REGION, Region.US_WEST_2) .put(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME, "s3") .put(AwsSignerExecutionAttribute.SIGNING_CLOCK, UTC_EPOCH_CLOCK) .build(); AwsS3V4Signer signer = AwsS3V4Signer.create(); SdkHttpFullRequest signedRequest = signer.presign(request, attributes); assertThat(signedRequest.firstMatchingRawQueryParameter("X-Amz-Signature")) .hasValue("3a9d36d37e9a554b7a3803f58ee7539b5d1f52fdfe89ce6fd40fb25762a35ec3"); } @Test public void signWithParams_doesNotFailWithEncodedCharacters() { URI target = URI.create("https://test.com/%20foo"); SdkHttpFullRequest request = SdkHttpFullRequest.builder() .method(SdkHttpMethod.GET) .uri(target) .encodedPath(target.getPath()) .build(); AwsS3V4Signer signer = AwsS3V4Signer.create(); assertDoesNotThrow(() -> signer.sign(request, AwsS3V4SignerParams.builder() .awsCredentials(AwsBasicCredentials.create("akid", "skid")) .signingRegion(Region.US_WEST_2) .signingName("s3") .build())); } @Test public void signWithExecutionAttributes_doesNotFailWithEncodedCharacters() { URI target = URI.create("https://test.com/%20foo"); SdkHttpFullRequest request = SdkHttpFullRequest.builder() .method(SdkHttpMethod.GET) .uri(target) .encodedPath(target.getPath()) .build(); ExecutionAttributes attributes = ExecutionAttributes.builder() .put(AwsSignerExecutionAttribute.AWS_CREDENTIALS, AwsBasicCredentials.create("akid", "skid")) .put(AwsSignerExecutionAttribute.SIGNING_REGION, Region.US_WEST_2) .put(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME, "s3") .build(); AwsS3V4Signer signer = AwsS3V4Signer.create(); assertDoesNotThrow(() -> signer.sign(request, attributes)); } @Test public void presignWithParams_doesNotFailWithEncodedCharacters() { URI target = URI.create("https://test.com/%20foo"); SdkHttpFullRequest request = SdkHttpFullRequest.builder() .method(SdkHttpMethod.GET) .uri(target) .encodedPath(target.getPath()) .build(); AwsS3V4Signer signer = AwsS3V4Signer.create(); assertDoesNotThrow(() -> signer.presign(request, Aws4PresignerParams.builder() .awsCredentials(AwsBasicCredentials.create("akid", "skid")) .signingRegion(Region.US_WEST_2) .signingName("s3") .build())); } @Test public void presignWithExecutionAttributes_doesNotFailWithEncodedCharacters() { URI target = URI.create("https://test.com/%20foo"); SdkHttpFullRequest request = SdkHttpFullRequest.builder() .method(SdkHttpMethod.GET) .uri(target) .encodedPath(target.getPath()) .build(); ExecutionAttributes attributes = ExecutionAttributes.builder() .put(AwsSignerExecutionAttribute.AWS_CREDENTIALS, AwsBasicCredentials.create("akid", "skid")) .put(AwsSignerExecutionAttribute.SIGNING_REGION, Region.US_WEST_2) .put(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME, "s3") .build(); AwsS3V4Signer signer = AwsS3V4Signer.create(); assertDoesNotThrow(() -> signer.presign(request, attributes)); } }
1,659
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer/Aws4EventStreamSignerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.signer; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static software.amazon.awssdk.auth.signer.internal.BaseEventStreamAsyncAws4Signer.EVENT_STREAM_DATE; import static software.amazon.awssdk.auth.signer.internal.BaseEventStreamAsyncAws4Signer.EVENT_STREAM_SIGNATURE; import io.reactivex.Flowable; import io.reactivex.functions.BiFunction; import io.reactivex.functions.Function; import io.reactivex.subscribers.TestSubscriber; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.time.Clock; import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneId; import java.time.ZoneOffset; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import java.util.stream.Stream; import org.assertj.core.util.Lists; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.signer.internal.SignerTestUtils; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.utils.BinaryUtils; import software.amazon.eventstream.HeaderValue; import software.amazon.eventstream.Message; import software.amazon.eventstream.MessageDecoder; /** * Unit tests for the {@link EventStreamAws4Signer}. */ public class Aws4EventStreamSignerTest { interface TestVector { SdkHttpFullRequest.Builder httpFullRequest(); List<String> requestBody(); AsyncRequestBody requestBodyPublisher(); Flowable<Message> expectedMessagePublisher(); } private static final List<Instant> SIGNING_INSTANTS = Stream.of( // Note: This first Instant is used for signing the request not an event OffsetDateTime.of(1981, 1, 16, 6, 30, 0, 0, ZoneOffset.UTC).toInstant(), OffsetDateTime.of(1981, 1, 16, 6, 30, 1, 0, ZoneOffset.UTC).toInstant(), OffsetDateTime.of(1981, 1, 16, 6, 30, 2, 0, ZoneOffset.UTC).toInstant(), OffsetDateTime.of(1981, 1, 16, 6, 30, 3, 0, ZoneOffset.UTC).toInstant(), OffsetDateTime.of(1981, 1, 16, 6, 30, 4, 0, ZoneOffset.UTC).toInstant() ).collect(Collectors.toList()); private EventStreamAws4Signer signer = EventStreamAws4Signer.create(); @Test public void testEventStreamSigning() { TestVector testVector = generateTestVector(); SdkHttpFullRequest.Builder request = testVector.httpFullRequest(); AwsBasicCredentials credentials = AwsBasicCredentials.create("access", "secret"); SdkHttpFullRequest signedRequest = SignerTestUtils.signRequest(signer, request.build(), credentials, "demo", signingClock(), "us-east-1"); AsyncRequestBody transformedPublisher = SignerTestUtils.signAsyncRequest(signer, signedRequest, testVector.requestBodyPublisher(), credentials, "demo", signingClock(), "us-east-1"); TestSubscriber testSubscriber = TestSubscriber.create(); Flowable.fromPublisher(transformedPublisher) .flatMap(new Function<ByteBuffer, Publisher<?>>() { Queue<Message> messages = new LinkedList<>(); MessageDecoder decoder = new MessageDecoder(message -> messages.offer(message)); @Override public Publisher<?> apply(ByteBuffer byteBuffer) throws Exception { decoder.feed(byteBuffer.array()); List<Message> messageList = new ArrayList<>(); while (!messages.isEmpty()) { messageList.add(messages.poll()); } return Flowable.fromIterable(messageList); } }) .subscribe(testSubscriber); testSubscriber.assertNoErrors(); testSubscriber.assertComplete(); testSubscriber.assertValueSequence(testVector.expectedMessagePublisher().blockingIterable()); } /** * Test that without demand from subscriber, trailing empty frame is not delivered */ @Test public void testBackPressure() { TestVector testVector = generateTestVector(); SdkHttpFullRequest.Builder request = testVector.httpFullRequest(); AwsBasicCredentials credentials = AwsBasicCredentials.create("access", "secret"); SdkHttpFullRequest signedRequest = SignerTestUtils.signRequest(signer, request.build(), credentials, "demo", signingClock(), "us-east-1"); AsyncRequestBody transformedPublisher = SignerTestUtils.signAsyncRequest(signer, signedRequest, testVector.requestBodyPublisher(), credentials, "demo", signingClock(), "us-east-1"); Subscriber<Object> subscriber = Mockito.spy(new Subscriber<Object>() { @Override public void onSubscribe(Subscription s) { //Only request the number of request body (excluding trailing empty frame) s.request(testVector.requestBody().size()); } @Override public void onNext(Object o) { } @Override public void onError(Throwable t) { fail("onError should never been called"); } @Override public void onComplete() { fail("onComplete should never been called"); } }); Flowable.fromPublisher(transformedPublisher) .flatMap(new Function<ByteBuffer, Publisher<?>>() { Queue<Message> messages = new LinkedList<>(); MessageDecoder decoder = new MessageDecoder(message -> messages.offer(message)); @Override public Publisher<?> apply(ByteBuffer byteBuffer) throws Exception { decoder.feed(byteBuffer.array()); List<Message> messageList = new ArrayList<>(); while (!messages.isEmpty()) { messageList.add(messages.poll()); } return Flowable.fromIterable(messageList); } }) .subscribe(subscriber); // The number of events equal to the size of request body (excluding trailing empty frame) verify(subscriber, times(testVector.requestBody().size())).onNext(any()); // subscriber is not terminated (no onError/onComplete) since trailing empty frame is not delivered yet verify(subscriber, never()).onError(any()); verify(subscriber, never()).onComplete(); } TestVector generateTestVector() { return new TestVector() { List<String> requestBody = Lists.newArrayList("A", "B", "C"); @Override public List<String> requestBody() { return requestBody; } @Override public SdkHttpFullRequest.Builder httpFullRequest() { //Header signature: "79f246d8652f08dd3cfaf84cc0d8b4fcce032332c78d43ea1ed6f4f6586ab59d"; //Signing key: "29dc0a760fed568677d74136ad02d315a07d31b8f321f5c43350f284dac892c"; return SdkHttpFullRequest.builder() .method(SdkHttpMethod.POST) .putHeader("Host", "demo.us-east-1.amazonaws.com") .putHeader("content-encoding", "application/vnd.amazon.eventstream") .putHeader("x-amz-content-sha256", "STREAMING-AWS4-HMAC-SHA256-EVENTS") .encodedPath("/streaming") .protocol("https") .host("demo.us-east-1.amazonaws.com"); } @Override public AsyncRequestBody requestBodyPublisher() { List<ByteBuffer> bodyBytes = requestBody.stream() .map(s -> ByteBuffer.wrap(s.getBytes(StandardCharsets.UTF_8))) .collect(Collectors.toList()); Publisher<ByteBuffer> bodyPublisher = Flowable.fromIterable(bodyBytes); return AsyncRequestBody.fromPublisher(bodyPublisher); } @Override public Flowable<Message> expectedMessagePublisher() { Flowable<String> sigsHex = Flowable.just( "7aabf85b765e6a4d0d500b6e968657b14726fa3e1eb7e839302728ffd77629a5", "f72aa9642f571d24a6e1ae42f10f073ad9448d8a028b6bcd82da081335adda02", "632af120435b57ec241d8bfbb12e496dfd5e2730a1a02ac0ab6eaa230ae02e9a", "c6f679ddb3af68f5e82f0cf6761244cb2338cf11e7d01a24130aea1b7c17e53e"); // The Last data frame is empty Flowable<String> payloads = Flowable.fromIterable(requestBody).concatWith(Flowable.just("")); return sigsHex.zipWith(payloads, new BiFunction<String, String, Message>() { // The first Instant was used to sign the request private int idx = 1; @Override public Message apply(String sig, String payload) throws Exception { Map<String, HeaderValue> headers = new HashMap<>(); headers.put(EVENT_STREAM_DATE, HeaderValue.fromTimestamp(SIGNING_INSTANTS.get(idx++))); headers.put(EVENT_STREAM_SIGNATURE, HeaderValue.fromByteArray(BinaryUtils.fromHex(sig))); return new Message(headers, payload.getBytes(StandardCharsets.UTF_8)); } } ); } }; } /** * @return A clock that returns the values from {@link #SIGNING_INSTANTS} in order. * @throws IllegalStateException When there are no more instants to return. */ private static Clock signingClock() { return new Clock() { private AtomicInteger timeIndex = new AtomicInteger(0); @Override public Instant instant() { int idx; // Note: we use an atomic because Clock must be threadsafe, // though probably not necessary for our tests if ((idx = timeIndex.getAndIncrement()) >= SIGNING_INSTANTS.size()) { throw new IllegalStateException("Clock ran out of Instants to return! " + idx); } return SIGNING_INSTANTS.get(idx); } @Override public ZoneId getZone() { return ZoneOffset.UTC; } @Override public Clock withZone(ZoneId zone) { throw new UnsupportedOperationException(); } }; } }
1,660
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer/Aws4SignerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.signer; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.mockito.Mockito.when; import java.io.ByteArrayInputStream; import java.net.URI; import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.time.Clock; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.SimpleTimeZone; import java.util.TimeZone; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentials; import software.amazon.awssdk.auth.signer.internal.Aws4SignerUtils; import software.amazon.awssdk.auth.signer.internal.SignerConstant; import software.amazon.awssdk.auth.signer.params.SignerChecksumParams; import software.amazon.awssdk.auth.signer.internal.SignerTestUtils; import software.amazon.awssdk.core.checksums.Algorithm; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; /** * Unit tests for the {@link Aws4Signer}. */ @RunWith(MockitoJUnitRunner.class) public class Aws4SignerTest { private static final String AWS_4_HMAC_SHA_256_AUTHORIZATION = "AWS4-HMAC-SHA256 Credential=access/19810216/us-east-1/demo/aws4_request, "; private static final String SIGNER_HEADER_WITH_CHECKSUMS_IN_HEADER = "SignedHeaders=host;x-amz-archive-description;x-amz-date;x-amzn-header-crc, "; private static final String SIGNER_HEADER_WITH_CHECKSUMS_IN_TRAILER = "SignedHeaders=host;x-amz-archive-description;x-amz-date;x-amz-trailer, "; private Aws4Signer signer = Aws4Signer.create(); @Mock private Clock signingOverrideClock; SdkHttpFullRequest.Builder request; AwsBasicCredentials credentials; @Before public void setupCase() { mockClock(); credentials = AwsBasicCredentials.create("access", "secret"); request = SdkHttpFullRequest.builder() .contentStreamProvider(() -> new ByteArrayInputStream("abc".getBytes())) .method(SdkHttpMethod.POST) .putHeader("Host", "demo.us-east-1.amazonaws.com") .putHeader("x-amz-archive-description", "test test") .encodedPath("/") .uri(URI.create("http://demo.us-east-1.amazonaws.com")); } @Test public void testSigning() throws Exception { final String expectedAuthorizationHeaderWithoutSha256Header = AWS_4_HMAC_SHA_256_AUTHORIZATION + "SignedHeaders=host;x-amz-archive-description;x-amz-date, " + "Signature=77fe7c02927966018667f21d1dc3dfad9057e58401cbb9ed64f1b7868288e35a"; final String expectedAuthorizationHeaderWithSha256Header = AWS_4_HMAC_SHA_256_AUTHORIZATION + "SignedHeaders=host;x-amz-archive-description;x-amz-date;x-amz-sha256, " + "Signature=e73e20539446307a5dc71252dbd5b97e861f1d1267456abda3ebd8d57e519951"; AwsBasicCredentials credentials = AwsBasicCredentials.create("access", "secret"); // Test request without 'x-amz-sha256' header SdkHttpFullRequest.Builder request = generateBasicRequest(); SdkHttpFullRequest signed = SignerTestUtils.signRequest(signer, request.build(), credentials, "demo", signingOverrideClock, "us-east-1"); assertThat(signed.firstMatchingHeader("Authorization")) .hasValue(expectedAuthorizationHeaderWithoutSha256Header); // Test request with 'x-amz-sha256' header request = generateBasicRequest(); request.putHeader("x-amz-sha256", "required"); signed = SignerTestUtils.signRequest(signer, request.build(), credentials, "demo", signingOverrideClock, "us-east-1"); assertThat(signed.firstMatchingHeader("Authorization")).hasValue(expectedAuthorizationHeaderWithSha256Header); } @Test public void queryParamsWithNullValuesAreStillSignedWithTrailingEquals() throws Exception { final String expectedAuthorizationHeaderWithoutSha256Header = AWS_4_HMAC_SHA_256_AUTHORIZATION + "SignedHeaders=host;x-amz-archive-description;x-amz-date, " + "Signature=c45a3ff1f028e83017f3812c06b4440f0b3240264258f6e18cd683b816990ba4"; AwsBasicCredentials credentials = AwsBasicCredentials.create("access", "secret"); // Test request without 'x-amz-sha256' header SdkHttpFullRequest.Builder request = generateBasicRequest().putRawQueryParameter("Foo", (String) null); SdkHttpFullRequest signed = SignerTestUtils.signRequest(signer, request.build(), credentials, "demo", signingOverrideClock, "us-east-1"); assertThat(signed.firstMatchingHeader("Authorization")).hasValue(expectedAuthorizationHeaderWithoutSha256Header); } @Test public void testPresigning() throws Exception { final String expectedAmzSignature = "bf7ae1c2f266d347e290a2aee7b126d38b8a695149d003b9fab2ed1eb6d6ebda"; final String expectedAmzCredentials = "access/19810216/us-east-1/demo/aws4_request"; final String expectedAmzHeader = "19810216T063000Z"; final String expectedAmzExpires = "604800"; AwsBasicCredentials credentials = AwsBasicCredentials.create("access", "secret"); // Test request without 'x-amz-sha256' header SdkHttpFullRequest request = generateBasicRequest().build(); SdkHttpFullRequest signed = SignerTestUtils.presignRequest(signer, request, credentials, null, "demo", signingOverrideClock, "us-east-1"); assertEquals(expectedAmzSignature, signed.rawQueryParameters().get("X-Amz-Signature").get(0)); assertEquals(expectedAmzCredentials, signed.rawQueryParameters().get("X-Amz-Credential").get(0)); assertEquals(expectedAmzHeader, signed.rawQueryParameters().get("X-Amz-Date").get(0)); assertEquals(expectedAmzExpires, signed.rawQueryParameters().get("X-Amz-Expires").get(0)); } /** * Tests that if passed anonymous credentials, signer will not generate a signature. */ @Test public void testAnonymous() throws Exception { AwsCredentials credentials = AnonymousCredentialsProvider.create().resolveCredentials(); SdkHttpFullRequest request = generateBasicRequest().build(); SignerTestUtils.signRequest(signer, request, credentials, "demo", signingOverrideClock, "us-east-1"); assertNull(request.headers().get("Authorization")); } /** * x-amzn-trace-id should not be signed as it may be mutated by proxies or load balancers. */ @Test public void xAmznTraceId_NotSigned() throws Exception { AwsBasicCredentials credentials = AwsBasicCredentials.create("akid", "skid"); SdkHttpFullRequest.Builder request = generateBasicRequest(); request.putHeader("X-Amzn-Trace-Id", " Root=1-584b150a-708479cb060007ffbf3ee1da;Parent=36d3dbcfd150aac9;Sampled=1"); SdkHttpFullRequest actual = SignerTestUtils.signRequest(signer, request.build(), credentials, "demo", signingOverrideClock, "us-east-1"); assertThat(actual.firstMatchingHeader("Authorization")) .hasValue("AWS4-HMAC-SHA256 Credential=akid/19810216/us-east-1/demo/aws4_request, " + "SignedHeaders=host;x-amz-archive-description;x-amz-date, " + "Signature=581d0042389009a28d461124138f1fe8eeb8daed87611d2a2b47fd3d68d81d73"); } /** * Multi-value headers should be comma separated. */ @Test public void canonicalizedHeaderString_multiValueHeaders_areCommaSeparated() throws Exception { AwsBasicCredentials credentials = AwsBasicCredentials.create("akid", "skid"); SdkHttpFullRequest.Builder request = generateBasicRequest(); request.appendHeader("foo","bar"); request.appendHeader("foo","baz"); SdkHttpFullRequest actual = SignerTestUtils.signRequest(signer, request.build(), credentials, "demo", signingOverrideClock, "us-east-1"); // We cannot easily test the canonical header string value, but the below signature asserts that it contains: // foo:bar,baz assertThat(actual.firstMatchingHeader("Authorization")) .hasValue("AWS4-HMAC-SHA256 Credential=akid/19810216/us-east-1/demo/aws4_request, " + "SignedHeaders=foo;host;x-amz-archive-description;x-amz-date, " + "Signature=1253bc1751048ea299e688cbe07a2224292e5cc606a079cb40459ad987793c19"); } /** * Canonical headers should remove excess white space before and after values, and convert sequential spaces to a single * space. */ @Test public void canonicalizedHeaderString_valuesWithExtraWhitespace_areTrimmed() throws Exception { AwsBasicCredentials credentials = AwsBasicCredentials.create("akid", "skid"); SdkHttpFullRequest.Builder request = generateBasicRequest(); request.putHeader("My-header1"," a b c "); request.putHeader("My-Header2"," \"a b c\" "); SdkHttpFullRequest actual = SignerTestUtils.signRequest(signer, request.build(), credentials, "demo", signingOverrideClock, "us-east-1"); // We cannot easily test the canonical header string value, but the below signature asserts that it contains: // my-header1:a b c // my-header2:"a b c" assertThat(actual.firstMatchingHeader("Authorization")) .hasValue("AWS4-HMAC-SHA256 Credential=akid/19810216/us-east-1/demo/aws4_request, " + "SignedHeaders=host;my-header1;my-header2;x-amz-archive-description;x-amz-date, " + "Signature=6d3520e3397e7aba593d8ebd8361fc4405e90aed71bc4c7a09dcacb6f72460b9"); } /** * Query strings with empty keys should not be included in the canonical string. */ @Test public void canonicalizedQueryString_keyWithEmptyNames_doNotGetSigned() throws Exception { AwsBasicCredentials credentials = AwsBasicCredentials.create("akid", "skid"); SdkHttpFullRequest.Builder request = generateBasicRequest(); request.putRawQueryParameter("", (String) null); SdkHttpFullRequest actual = SignerTestUtils.signRequest(signer, request.build(), credentials, "demo", signingOverrideClock, "us-east-1"); assertThat(actual.firstMatchingHeader("Authorization")) .hasValue("AWS4-HMAC-SHA256 Credential=akid/19810216/us-east-1/demo/aws4_request, " + "SignedHeaders=host;x-amz-archive-description;x-amz-date, " + "Signature=581d0042389009a28d461124138f1fe8eeb8daed87611d2a2b47fd3d68d81d73"); } private SdkHttpFullRequest.Builder generateBasicRequest() { return SdkHttpFullRequest.builder() .contentStreamProvider(() -> new ByteArrayInputStream("{\"TableName\": \"foo\"}".getBytes())) .method(SdkHttpMethod.POST) .putHeader("Host", "demo.us-east-1.amazonaws.com") .putHeader("x-amz-archive-description", "test test") .encodedPath("/") .uri(URI.create("http://demo.us-east-1.amazonaws.com")); } private void mockClock() { Calendar c = new GregorianCalendar(); c.set(1981, 1, 16, 6, 30, 0); c.setTimeZone(TimeZone.getTimeZone("UTC")); when(signingOverrideClock.millis()).thenReturn(c.getTimeInMillis()); } private String getOldTimeStamp(Date date) { final SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'"); dateTimeFormat.setTimeZone(new SimpleTimeZone(0, "UTC")); return dateTimeFormat.format(date); } @Test public void getTimeStamp() { Date now = new Date(); String timeStamp = Aws4SignerUtils.formatTimestamp(now.getTime()); String old = getOldTimeStamp(now); assertEquals(old, timeStamp); } private String getOldDateStamp(Date date) { final SimpleDateFormat dateStampFormat = new SimpleDateFormat("yyyyMMdd"); dateStampFormat.setTimeZone(new SimpleTimeZone(0, "UTC")); return dateStampFormat.format(date); } @Test public void getDateStamp() { Date now = new Date(); String dateStamp = Aws4SignerUtils.formatDateStamp(now.getTime()); String old = getOldDateStamp(now); assertEquals(old, dateStamp); } @Test public void signing_with_Crc32Checksum_WithOut_x_amz_sha25_header() throws Exception { //Note here x_amz_sha25_header is not present in SignedHeaders String expectedAuthorization = AWS_4_HMAC_SHA_256_AUTHORIZATION + SIGNER_HEADER_WITH_CHECKSUMS_IN_HEADER + "Signature=c1804802dc623d1689e7d0a7f9f5caee3588cc8d3df4495425129dbd52965d1f"; final SignerChecksumParams signerChecksumParams = SignerChecksumParams.builder() .algorithm(Algorithm.CRC32) .checksumHeaderName("x-amzn-header-crc") .isStreamingRequest(false) .build(); SdkHttpFullRequest signed = SignerTestUtils.signRequest(signer, request.contentStreamProvider( () -> new ByteArrayInputStream("{\"TableName\": \"foo\"}".getBytes(StandardCharsets.UTF_8)) ).build(), credentials, "demo", signingOverrideClock, "us-east-1", signerChecksumParams); assertThat(signed.firstMatchingHeader("x-amzn-header-crc").get()).contains("oL+a/g=="); assertThat(signed.firstMatchingHeader(SignerConstant.X_AMZ_CONTENT_SHA256)).isNotPresent(); assertThat(signed.firstMatchingHeader("Authorization")).hasValue(expectedAuthorization); } @Test public void signing_with_Crc32Checksum_with_streaming_input_request() throws Exception { //Note here x_amz_sha25_header is not present in SignedHeaders String expectedAuthorization = AWS_4_HMAC_SHA_256_AUTHORIZATION + SIGNER_HEADER_WITH_CHECKSUMS_IN_HEADER + "Signature=c1804802dc623d1689e7d0a7f9f5caee3588cc8d3df4495425129dbd52965d1f"; final SignerChecksumParams signerChecksumParams = SignerChecksumParams.builder() .algorithm(Algorithm.CRC32) .checksumHeaderName("x-amzn-header-crc") .isStreamingRequest(true) .build(); SdkHttpFullRequest signed = SignerTestUtils.signRequest(signer, request.contentStreamProvider( () -> new ByteArrayInputStream("{\"TableName\": \"foo\"}".getBytes(StandardCharsets.UTF_8)) ).build(), credentials, "demo", signingOverrideClock, "us-east-1", signerChecksumParams); assertThat(signed.firstMatchingHeader("x-amzn-header-crc").get()).contains("oL+a/g=="); assertThat(signed.firstMatchingHeader(SignerConstant.X_AMZ_CONTENT_SHA256)).isNotPresent(); assertThat(signed.firstMatchingHeader("Authorization")).hasValue(expectedAuthorization); } @Test public void signing_with_Crc32Checksum_with_x_amz_sha25_header_preset() throws Exception { //Note here x_amz_sha25_header is present in SignedHeaders, we make sure checksum is calculated even in this case. String expectedAuthorization = AWS_4_HMAC_SHA_256_AUTHORIZATION + "SignedHeaders=host;x-amz-archive-description;x-amz-content-sha256;x-amz-date;x-amzn-header-crc, " + "Signature=bc931232666f226854cdd9c9962dc03d791cf4024f5ca032fab996c1d15e4a5d"; final SignerChecksumParams signerChecksumParams = SignerChecksumParams.builder() .algorithm(Algorithm.CRC32) .checksumHeaderName("x-amzn-header-crc") .isStreamingRequest(true).build(); request = generateBasicRequest(); // presetting of the header request.putHeader(SignerConstant.X_AMZ_CONTENT_SHA256, "required"); SdkHttpFullRequest signed = SignerTestUtils.signRequest(signer, request.build(), credentials, "demo", signingOverrideClock, "us-east-1", signerChecksumParams); assertThat(signed.firstMatchingHeader("Authorization")).hasValue(expectedAuthorization); assertThat(signed.firstMatchingHeader("x-amzn-header-crc").get()).contains("oL+a/g=="); assertThat(signed.firstMatchingHeader(SignerConstant.X_AMZ_CONTENT_SHA256)).isPresent(); } @Test public void signing_with_NoHttpChecksum_As_No_impact_on_Signature() throws Exception { //Note here x_amz_sha25_header is not present in SignedHeaders String expectedAuthorization = AWS_4_HMAC_SHA_256_AUTHORIZATION + "SignedHeaders=host;x-amz-archive-description;x-amz-date, " + "Signature=77fe7c02927966018667f21d1dc3dfad9057e58401cbb9ed64f1b7868288e35a"; SdkHttpFullRequest signed = SignerTestUtils.signRequest(signer, request.contentStreamProvider( () -> new ByteArrayInputStream("{\"TableName\": \"foo\"}".getBytes(StandardCharsets.UTF_8)) ).build(), credentials, "demo", signingOverrideClock, "us-east-1", null); assertThat(signed.firstMatchingHeader("Authorization")).hasValue(expectedAuthorization); assertThat(signed.firstMatchingHeader("x-amzn-header-crc")).isNotPresent(); } @Test public void signing_with_Crc32Checksum_with_header_already_present() throws Exception { String expectedAuthorization = AWS_4_HMAC_SHA_256_AUTHORIZATION + SIGNER_HEADER_WITH_CHECKSUMS_IN_HEADER + "Signature=f6fad563460f2ac50fe2ab5f5f5d77a787e357897ac6e9bb116ff12d30f45589"; final SignerChecksumParams signerChecksumParams = SignerChecksumParams.builder() .algorithm(Algorithm.CRC32) .checksumHeaderName("x-amzn-header-crc") .isStreamingRequest(false) .build(); SdkHttpFullRequest signed = SignerTestUtils.signRequest(signer, request.contentStreamProvider( () -> new ByteArrayInputStream("{\"TableName\": \"foo\"}".getBytes(StandardCharsets.UTF_8)) ) .appendHeader("x-amzn-header-crc", "preCalculatedChecksum") .build(), credentials, "demo", signingOverrideClock, "us-east-1", signerChecksumParams); assertThat(signed.firstMatchingHeader("x-amzn-header-crc")).hasValue("preCalculatedChecksum"); assertThat(signed.firstMatchingHeader(SignerConstant.X_AMZ_CONTENT_SHA256)).isNotPresent(); assertThat(signed.firstMatchingHeader("Authorization")).hasValue(expectedAuthorization); } @Test public void signing_with_Crc32Checksum_with__trailer_header_already_present() throws Exception { String expectedAuthorization = AWS_4_HMAC_SHA_256_AUTHORIZATION + SIGNER_HEADER_WITH_CHECKSUMS_IN_TRAILER + "Signature=3436c4bc175d31e87a591802e64756cebf2d1c6c2054d26ca3dc91bdd3de303e"; final SignerChecksumParams signerChecksumParams = SignerChecksumParams.builder() .algorithm(Algorithm.CRC32) .checksumHeaderName("x-amzn-header-crc") .isStreamingRequest(false) .build(); SdkHttpFullRequest signed = SignerTestUtils.signRequest( signer, request.contentStreamProvider(() -> new ByteArrayInputStream(("{\"TableName" + "\": " + "\"foo\"}").getBytes(StandardCharsets.UTF_8))) .appendHeader("x-amz-trailer", "x-amzn-header-crc") .build(), credentials, "demo", signingOverrideClock, "us-east-1", signerChecksumParams); assertThat(signed.firstMatchingHeader("x-amzn-header-crc")).isNotPresent(); assertThat(signed.firstMatchingHeader("x-amz-trailer")).contains("x-amzn-header-crc"); assertThat(signed.firstMatchingHeader(SignerConstant.X_AMZ_CONTENT_SHA256)).isNotPresent(); assertThat(signed.firstMatchingHeader("Authorization")).hasValue(expectedAuthorization); } }
1,661
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer/Aws4UnsignedPayloadSignerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.signer; import java.io.ByteArrayInputStream; import java.net.URI; import java.time.Clock; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.TimeZone; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.signer.params.Aws4SignerParams; import software.amazon.awssdk.auth.signer.params.SignerChecksumParams; import software.amazon.awssdk.core.checksums.Algorithm; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.regions.Region; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class Aws4UnsignedPayloadSignerTest { final static SignerChecksumParams CRC32_HEADER_SIGNER_PARAMS = SignerChecksumParams.builder() .algorithm(Algorithm.CRC32) .checksumHeaderName("x-amzn-header-crc") .isStreamingRequest(false) .build(); AwsBasicCredentials credentials; Aws4SignerParams signerParams; @Mock private Clock signingOverrideClock; @Before public void setupCase() { mockClock(); credentials = AwsBasicCredentials.create("access", "secret"); signerParams = Aws4SignerParams.builder() .awsCredentials(credentials) .signingName("demo") .checksumParams(CRC32_HEADER_SIGNER_PARAMS) .signingClockOverride(signingOverrideClock) .signingRegion(Region.of("us-east-1")) .build(); } @Test public void testAws4UnsignedPayloadSignerUsingHttpWherePayloadIsSigned() { final Aws4UnsignedPayloadSigner signer = Aws4UnsignedPayloadSigner.create(); SdkHttpFullRequest.Builder request = getHttpRequestBuilder("abc", "http"); SdkHttpFullRequest signed = signer.sign(request.build(), signerParams); assertThat(signed.firstMatchingHeader("x-amzn-header-crc")).hasValue("NSRBwg=="); } @Test public void testAws4UnsignedPayloadSignerWithHttpsRequest() { final Aws4UnsignedPayloadSigner signer = Aws4UnsignedPayloadSigner.create(); SdkHttpFullRequest.Builder request = getHttpRequestBuilder("abc", "https"); SdkHttpFullRequest signed = signer.sign(request.build(), signerParams); assertThat(signed.firstMatchingHeader("x-amzn-header-crc")).isNotPresent(); } private void mockClock() { Calendar c = new GregorianCalendar(); c.set(1981, 1, 16, 6, 30, 0); c.setTimeZone(TimeZone.getTimeZone("UTC")); when(signingOverrideClock.millis()).thenReturn(c.getTimeInMillis()); } private SdkHttpFullRequest.Builder getHttpRequestBuilder(String testString, String protocol) { SdkHttpFullRequest.Builder request = SdkHttpFullRequest.builder() .contentStreamProvider(() -> new ByteArrayInputStream(testString.getBytes())) .method(SdkHttpMethod.POST) .putHeader("Host", "demo.us-east-1.amazonaws.com") .putHeader("x-amz-archive-description", "test test") .encodedPath("/") .protocol(protocol) .uri(URI.create(protocol + "://demo.us-east-1.amazonaws.com")); return request; } }
1,662
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer/AwsSignerExecutionAttributeTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.signer; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import static software.amazon.awssdk.checksums.DefaultChecksumAlgorithm.CRC32; import static software.amazon.awssdk.checksums.DefaultChecksumAlgorithm.SHA256; import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; import java.util.Collections; import java.util.concurrent.CompletableFuture; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import software.amazon.awssdk.auth.credentials.AwsCredentials; import software.amazon.awssdk.core.SelectedAuthScheme; import software.amazon.awssdk.core.checksums.Algorithm; import software.amazon.awssdk.core.checksums.ChecksumSpecs; import software.amazon.awssdk.core.interceptor.ExecutionAttribute; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute; import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute; import software.amazon.awssdk.http.auth.aws.signer.AwsV4FamilyHttpSigner; import software.amazon.awssdk.http.auth.aws.signer.AwsV4HttpSigner; import software.amazon.awssdk.http.auth.aws.signer.AwsV4aHttpSigner; import software.amazon.awssdk.http.auth.aws.signer.RegionSet; import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeOption; import software.amazon.awssdk.http.auth.spi.signer.HttpSigner; import software.amazon.awssdk.http.auth.spi.signer.SignerProperty; import software.amazon.awssdk.identity.spi.Identity; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.RegionScope; class AwsSignerExecutionAttributeTest { private static final SelectedAuthScheme<Identity> EMPTY_SELECTED_AUTH_SCHEME = new SelectedAuthScheme<>(CompletableFuture.completedFuture(Mockito.mock(Identity.class)), (HttpSigner<Identity>) Mockito.mock(HttpSigner.class), AuthSchemeOption.builder().schemeId("mock").build()); private ExecutionAttributes attributes; private Clock testClock; @BeforeEach public void setup() { this.attributes = new ExecutionAttributes(); this.testClock = Clock.fixed(Instant.now(), ZoneOffset.UTC); } @Test public void awsCredentials_oldAndNewAttributeAreMirrored() { AwsCredentials creds = Mockito.mock(AwsCredentials.class); // If selected auth scheme is null, writing non-null old property can be read with new property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, null); attributes.putAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS, creds); assertThat(attributes.getAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME).identity().join()).isSameAs(creds); // If selected auth scheme is null, writing null to old property can be read with new property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, null); attributes.putAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS, null); assertThat(attributes.getAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME).identity().join()).isNull(); // If selected auth scheme is non-null, writing non-null to old property can be read with new property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, EMPTY_SELECTED_AUTH_SCHEME); attributes.putAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS, creds); assertThat(attributes.getAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME).identity().join()).isSameAs(creds); // If selected auth scheme is non-null, writing null to old property can be read with new property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, EMPTY_SELECTED_AUTH_SCHEME); attributes.putAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS, null); assertThat(attributes.getAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME).identity().join()).isNull(); // Writing non-null new property can be read with old property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, new SelectedAuthScheme<>(CompletableFuture.completedFuture(creds), EMPTY_SELECTED_AUTH_SCHEME.signer(), EMPTY_SELECTED_AUTH_SCHEME.authSchemeOption())); assertThat(attributes.getAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS)).isSameAs(creds); // Writing null new property can be read with old property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, new SelectedAuthScheme<>(CompletableFuture.completedFuture(null), EMPTY_SELECTED_AUTH_SCHEME.signer(), EMPTY_SELECTED_AUTH_SCHEME.authSchemeOption())); assertThat(attributes.getAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS)).isNull(); // Null selected auth scheme can be read with old property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, null); assertThat(attributes.getAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS)).isNull(); } @Test public void signingRegion_oldAndNewAttributeAreMirrored() { assertOldAndNewAttributesAreMirrored(AwsSignerExecutionAttribute.SIGNING_REGION, AwsV4HttpSigner.REGION_NAME, Region.US_EAST_1, "us-east-1"); } @Test public void signingRegionScope_oldAndNewAttributeAreMirrored() { assertOldAndNewAttributesAreMirrored(AwsSignerExecutionAttribute.SIGNING_REGION_SCOPE, AwsV4aHttpSigner.REGION_SET, RegionScope.create("foo"), RegionSet.create("foo") ); } @Test public void signingRegionScope_mappingToOldWithMoreThanOneRegionThrows() { RegionSet regionSet = RegionSet.create("foo1,foo2"); AuthSchemeOption newOption = EMPTY_SELECTED_AUTH_SCHEME.authSchemeOption().copy(o -> o.putSignerProperty(AwsV4aHttpSigner.REGION_SET, regionSet)); attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, new SelectedAuthScheme<>(EMPTY_SELECTED_AUTH_SCHEME.identity(), EMPTY_SELECTED_AUTH_SCHEME.signer(), newOption)); assertThrows(IllegalArgumentException.class, () -> attributes.getAttribute(AwsSignerExecutionAttribute.SIGNING_REGION_SCOPE)); } @Test public void signingName_oldAndNewAttributeAreMirrored() { assertOldAndNewAttributesAreMirrored(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME, AwsV4FamilyHttpSigner.SERVICE_SIGNING_NAME, "ServiceName"); } @Test public void doubleUrlEncode_oldAndNewAttributeAreMirrored() { assertOldAndNewBooleanAttributesAreMirrored(AwsSignerExecutionAttribute.SIGNER_DOUBLE_URL_ENCODE, AwsV4FamilyHttpSigner.DOUBLE_URL_ENCODE); } @Test public void signerNormalizePath_oldAndNewAttributeAreMirrored() { assertOldAndNewBooleanAttributesAreMirrored(AwsSignerExecutionAttribute.SIGNER_NORMALIZE_PATH, AwsV4FamilyHttpSigner.NORMALIZE_PATH); } @Test public void signingClock_oldAndNewAttributeAreMirrored() { assertOldAndNewAttributesAreMirrored(AwsSignerExecutionAttribute.SIGNING_CLOCK, HttpSigner.SIGNING_CLOCK, Mockito.mock(Clock.class)); } @Test public void checksum_AttributeWriteReflectedInProperty() { assertOldAttributeWrite_canBeReadFromNewAttributeCases(SdkExecutionAttribute.RESOLVED_CHECKSUM_SPECS, AwsV4FamilyHttpSigner.CHECKSUM_ALGORITHM, ChecksumSpecs.builder() .isRequestChecksumRequired(true) .headerName("beepboop") .isRequestStreaming(true) .isValidationEnabled(true) .responseValidationAlgorithms( Collections.singletonList(Algorithm.CRC32)) .algorithm(Algorithm.SHA256) .build(), SHA256); } @Test public void checksum_PropertyWriteReflectedInAttribute() { ChecksumSpecs initialValue = ChecksumSpecs.builder() .isRequestChecksumRequired(true) .headerName("x-amz-checksum-sha256") .isRequestStreaming(true) .isValidationEnabled(true) .responseValidationAlgorithms( Collections.singletonList(Algorithm.CRC32)) .algorithm(Algorithm.SHA256) .build(); attributes.putAttribute(SdkExecutionAttribute.RESOLVED_CHECKSUM_SPECS, initialValue); assertNewPropertyWrite_canBeReadFromNewAttribute(SdkExecutionAttribute.RESOLVED_CHECKSUM_SPECS, AwsV4FamilyHttpSigner.CHECKSUM_ALGORITHM, initialValue, SHA256); } @Test public void checksum_NullPropertyWriteReflectedInAttribute() { ChecksumSpecs initialValue = ChecksumSpecs.builder() .isRequestChecksumRequired(true) .headerName("x-amz-checksum-sha256") .isRequestStreaming(true) .isValidationEnabled(true) .responseValidationAlgorithms( Collections.singletonList(Algorithm.CRC32)) .algorithm(Algorithm.SHA256) .build(); attributes.putAttribute(SdkExecutionAttribute.RESOLVED_CHECKSUM_SPECS, initialValue); ChecksumSpecs expectedValue = ChecksumSpecs.builder() .isRequestChecksumRequired(true) .isRequestStreaming(true) .isValidationEnabled(true) .responseValidationAlgorithms( Collections.singletonList(Algorithm.CRC32)) .build(); assertNewPropertyWrite_canBeReadFromNewAttribute(SdkExecutionAttribute.RESOLVED_CHECKSUM_SPECS, AwsV4FamilyHttpSigner.CHECKSUM_ALGORITHM, expectedValue, null); } @Test public void checksum_PropertyWriteReflectedInAttributeAndHeaderName() { // We need to set up the attribute first, so that ChecksumSpecs information is not lost ChecksumSpecs valueToWrite = ChecksumSpecs.builder() .isRequestChecksumRequired(true) .headerName("x-amz-checksum-sha256") .isRequestStreaming(true) .isValidationEnabled(true) .responseValidationAlgorithms( Collections.singletonList(Algorithm.CRC32)) .algorithm(Algorithm.SHA256) .build(); attributes.putAttribute(SdkExecutionAttribute.RESOLVED_CHECKSUM_SPECS, valueToWrite); // The header name should be updated to reflect the change in algorithm ChecksumSpecs expectedValue = ChecksumSpecs.builder() .isRequestChecksumRequired(true) .headerName("x-amz-checksum-crc32") .isRequestStreaming(true) .isValidationEnabled(true) .responseValidationAlgorithms( Collections.singletonList(Algorithm.CRC32)) .algorithm(Algorithm.CRC32) .build(); assertNewPropertyWrite_canBeReadFromNewAttribute(SdkExecutionAttribute.RESOLVED_CHECKSUM_SPECS, AwsV4FamilyHttpSigner.CHECKSUM_ALGORITHM, expectedValue, CRC32); } private void assertOldAndNewBooleanAttributesAreMirrored(ExecutionAttribute<Boolean> attribute, SignerProperty<Boolean> property) { assertOldAndNewAttributesAreMirrored(attribute, property, true); assertOldAndNewAttributesAreMirrored(attribute, property, false); } private <T> void assertOldAndNewAttributesAreMirrored(ExecutionAttribute<T> attributeToWrite, SignerProperty<T> propertyToRead, T valueToWrite) { assertOldAndNewAttributesAreMirrored(attributeToWrite, propertyToRead, valueToWrite, valueToWrite); } private <T, U> void assertOldAndNewAttributesAreMirrored(ExecutionAttribute<T> oldAttribute, SignerProperty<U> newProperty, T oldPropertyValue, U newPropertyValue) { assertOldAttributeWrite_canBeReadFromNewAttributeCases(oldAttribute, newProperty, oldPropertyValue, newPropertyValue); assertNewPropertyWrite_canBeReadFromNewAttributeCases(oldAttribute, newProperty, oldPropertyValue, newPropertyValue); // Null selected auth scheme can be read with old property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, null); assertThat(attributes.getAttribute(oldAttribute)).isNull(); } private <T, U> void assertNewPropertyWrite_canBeReadFromNewAttribute(ExecutionAttribute<T> oldAttribute, SignerProperty<U> newProperty, T oldPropertyValue, U newPropertyValue) { AuthSchemeOption newOption = EMPTY_SELECTED_AUTH_SCHEME.authSchemeOption().copy(o -> o.putSignerProperty(newProperty, newPropertyValue)); attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, new SelectedAuthScheme<>(EMPTY_SELECTED_AUTH_SCHEME.identity(), EMPTY_SELECTED_AUTH_SCHEME.signer(), newOption)); assertThat(attributes.getAttribute(oldAttribute)).isEqualTo(oldPropertyValue); } private <T, U> void assertNewPropertyWrite_canBeReadFromNewAttributeCases(ExecutionAttribute<T> attributeToWrite, SignerProperty<U> propertyToRead, T valueToWrite, U propertyToExpect) { // Writing non-null new property can be read with old property assertNewPropertyWrite_canBeReadFromNewAttribute(attributeToWrite, propertyToRead, valueToWrite, propertyToExpect); // Writing null new property can be read with old property assertNewPropertyWrite_canBeReadFromNewAttribute(attributeToWrite, propertyToRead, null, null); } private <T, U> void assertOldAttributeWrite_canBeReadFromNewAttribute(ExecutionAttribute<T> attributeToWrite, SignerProperty<U> propertyToRead, T valueToWrite, U propertyToExpect) { attributes.putAttribute(attributeToWrite, valueToWrite); assertThat(attributes.getAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME) .authSchemeOption() .signerProperty(propertyToRead)).isEqualTo(propertyToExpect); } private <T, U> void assertOldAttributeWrite_canBeReadFromNewAttributeCases(ExecutionAttribute<T> attributeToWrite, SignerProperty<U> propertyToRead, T valueToWrite, U propertyToExpect) { // If selected auth scheme is null, writing non-null old property can be read with new property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, null); assertOldAttributeWrite_canBeReadFromNewAttribute(attributeToWrite, propertyToRead, valueToWrite, propertyToExpect); // If selected auth scheme is null, writing null to old property can be read with new property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, null); assertOldAttributeWrite_canBeReadFromNewAttribute(attributeToWrite, propertyToRead, null, null); // If selected auth scheme is non-null, writing non-null to old property can be read with new property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, EMPTY_SELECTED_AUTH_SCHEME); assertOldAttributeWrite_canBeReadFromNewAttribute(attributeToWrite, propertyToRead, valueToWrite, propertyToExpect); // If selected auth scheme is non-null, writing null to old property can be read with new property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, EMPTY_SELECTED_AUTH_SCHEME); assertOldAttributeWrite_canBeReadFromNewAttribute(attributeToWrite, propertyToRead, null, null); } }
1,663
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer/AbstractAws4SignerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.signer; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.signer.internal.AbstractAws4Signer; public class AbstractAws4SignerTest { @Test public void test() { assertEquals( "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", AbstractAws4Signer.EMPTY_STRING_SHA256_HEX); } }
1,664
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer/internal/Aws4SignerRequestParamsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.signer.internal; import static org.assertj.core.api.Assertions.assertThat; import java.time.Duration; import java.time.Instant; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.signer.params.Aws4SignerParams; import software.amazon.awssdk.regions.Region; /** * Tests for {@link Aws4SignerRequestParams}. */ public class Aws4SignerRequestParamsTest { @Test public void appliesOffset_PositiveOffset() { offsetTest(5); } @Test public void appliesOffset_NegativeOffset() { offsetTest(-5); } private void offsetTest(int offsetSeconds) { Aws4SignerParams signerParams = Aws4SignerParams.builder() .awsCredentials(AwsBasicCredentials.create("akid", "skid")) .doubleUrlEncode(false) .signingName("test-service") .signingRegion(Region.US_WEST_2) .timeOffset(offsetSeconds) .build(); Instant now = Instant.now(); Aws4SignerRequestParams requestParams = new Aws4SignerRequestParams(signerParams); Instant requestSigningInstant = Instant.ofEpochMilli(requestParams.getRequestSigningDateTimeMilli()); // The offset is subtracted from the current time if (offsetSeconds > 0) { assertThat(requestSigningInstant).isBefore(now); } else { assertThat(requestSigningInstant).isAfter(now); } Duration diff = Duration.between(requestSigningInstant, now.minusSeconds(offsetSeconds)); // Allow some wiggle room in the difference since we can't use a clock // override for complete accuracy as it doesn't apply the offset when // using a clock override assertThat(diff).isLessThanOrEqualTo(Duration.ofMillis(100)); } }
1,665
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer/internal/AwsChunkedEncodingInputStreamTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.signer.internal; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.when; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.core.internal.chunked.AwsChunkedEncodingConfig; import software.amazon.awssdk.auth.signer.internal.chunkedencoding.AwsSignedChunkedEncodingInputStream; import software.amazon.awssdk.auth.signer.internal.chunkedencoding.AwsS3V4ChunkSigner; /** * Runs unit tests that check that the class AwsChunkedEncodingInputStream supports params required for Sigv4 chunk * signing. */ @RunWith(MockitoJUnitRunner.class) public class AwsChunkedEncodingInputStreamTest { private static final String REQUEST_SIGNATURE = "a0c7e7324d9c209c4a86a1c1452d60862591b7370a725364d52ba490210f2d9d"; private static final String CHUNK_SIGNATURE_1 = "3d5a2da1f773f64fdde2c6ca7d18c4bfee2a5a76b8153854c2a722c3fe8549cc"; private static final String CHUNK_SIGNATURE_2 = "0362eef10ceccf47fc1bf944a9df45a3e7dd5ea936e118b00e3d649b1d825f2f"; private static final String CHUNK_SIGNATURE_3 = "4722d8dac986015bdabeb5fafcb45db7b5585329befa485849c4938fed2aaaa2"; private static final String SIGNATURE_KEY = "chunk-signature="; private static final String EMPTY_STRING = ""; private static final String CRLF = "\r\n"; private static final int DEFAULT_CHUNK_SIZE = 128 * 1024; private static final int SIGV4_CHUNK_SIGNATURE_LENGTH = 64; @Mock AwsS3V4ChunkSigner chunkSigner; @Test public void streamContentLength_smallObject_calculatedCorrectly() { long streamContentLength = AwsSignedChunkedEncodingInputStream.calculateStreamContentLength(10, SIGV4_CHUNK_SIGNATURE_LENGTH, AwsChunkedEncodingConfig.create()); assertThat(streamContentLength).isEqualTo(182); } @Test public void streamContentLength_largeObject_calculatedCorrectly() { long streamContentLength = AwsSignedChunkedEncodingInputStream.calculateStreamContentLength(DEFAULT_CHUNK_SIZE + 10, SIGV4_CHUNK_SIGNATURE_LENGTH, AwsChunkedEncodingConfig.create()); assertThat(streamContentLength).isEqualTo(131344); } @Test public void streamContentLength_differentChunkSize_calculatedCorrectly() { int chunkSize = 64 * 1024; AwsChunkedEncodingConfig chunkConfig = AwsChunkedEncodingConfig.builder().chunkSize(chunkSize).build(); long streamContentLength = AwsSignedChunkedEncodingInputStream.calculateStreamContentLength(chunkSize + 10, SIGV4_CHUNK_SIGNATURE_LENGTH, chunkConfig); assertThat(streamContentLength).isEqualTo(65808); } @Test(expected = IllegalArgumentException.class) public void streamContentLength_negative_throwsException() { AwsSignedChunkedEncodingInputStream.calculateStreamContentLength(-1, SIGV4_CHUNK_SIGNATURE_LENGTH, AwsChunkedEncodingConfig.create()); } @Test public void chunkedEncodingStream_smallObject_createsCorrectChunks() throws IOException { when(chunkSigner.signChunk(any(), any())).thenReturn(CHUNK_SIGNATURE_1) .thenReturn(CHUNK_SIGNATURE_2); String chunkData = "helloworld"; ByteArrayInputStream input = new ByteArrayInputStream(chunkData.getBytes()); AwsSignedChunkedEncodingInputStream stream = AwsSignedChunkedEncodingInputStream.builder() .inputStream(input) .awsChunkSigner(chunkSigner) .headerSignature(REQUEST_SIGNATURE) .awsChunkedEncodingConfig(AwsChunkedEncodingConfig.create()) .build(); int expectedChunks = 2; consumeAndVerify(stream, expectedChunks); Mockito.verify(chunkSigner, times(1)).signChunk(chunkData.getBytes(StandardCharsets.UTF_8), REQUEST_SIGNATURE); Mockito.verify(chunkSigner, times(1)).signChunk(EMPTY_STRING.getBytes(StandardCharsets.UTF_8), CHUNK_SIGNATURE_1); } @Test public void chunkedEncodingStream_largeObject_createsCorrectChunks() throws IOException { when(chunkSigner.signChunk(any(), any())).thenReturn(CHUNK_SIGNATURE_1) .thenReturn(CHUNK_SIGNATURE_2) .thenReturn(CHUNK_SIGNATURE_3); String chunk1Data = StringUtils.repeat('a', DEFAULT_CHUNK_SIZE); String chunk2Data = "a"; ByteArrayInputStream input = new ByteArrayInputStream(chunk1Data.concat(chunk2Data).getBytes()); AwsSignedChunkedEncodingInputStream stream = AwsSignedChunkedEncodingInputStream.builder() .inputStream(input) .headerSignature(REQUEST_SIGNATURE) .awsChunkSigner(chunkSigner) .awsChunkedEncodingConfig(AwsChunkedEncodingConfig.create()) .build(); int expectedChunks = 3; consumeAndVerify(stream, expectedChunks); Mockito.verify(chunkSigner, times(1)).signChunk(chunk1Data.getBytes(StandardCharsets.UTF_8), REQUEST_SIGNATURE); Mockito.verify(chunkSigner, times(1)).signChunk(chunk2Data.getBytes(StandardCharsets.UTF_8), CHUNK_SIGNATURE_1); Mockito.verify(chunkSigner, times(1)).signChunk(EMPTY_STRING.getBytes(StandardCharsets.UTF_8), CHUNK_SIGNATURE_2); } @Test public void chunkedEncodingStream_emptyString_createsCorrectChunks() throws IOException { when(chunkSigner.signChunk(any(), any())).thenReturn(CHUNK_SIGNATURE_1); String chunkData = EMPTY_STRING; ByteArrayInputStream input = new ByteArrayInputStream(chunkData.getBytes()); AwsSignedChunkedEncodingInputStream stream = AwsSignedChunkedEncodingInputStream.builder() .inputStream(input) .awsChunkSigner(chunkSigner) .headerSignature(REQUEST_SIGNATURE) .awsChunkedEncodingConfig(AwsChunkedEncodingConfig.create()).build(); int expectedChunks = 1; consumeAndVerify(stream, expectedChunks); Mockito.verify(chunkSigner, times(1)).signChunk(chunkData.getBytes(StandardCharsets.UTF_8), REQUEST_SIGNATURE); } private void consumeAndVerify(AwsSignedChunkedEncodingInputStream stream, int numChunks) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); IOUtils.copy(stream, output); String result = new String(output.toByteArray(), StandardCharsets.UTF_8); assertChunks(result, numChunks); } private void assertChunks(String result, int numExpectedChunks) { List<String> lines = Stream.of(result.split(CRLF)).collect(Collectors.toList()); assertThat(lines.size()).isEqualTo(numExpectedChunks * 2 - 1); for (int i = 0; i < lines.size(); i = i + 2) { String chunkMetadata = lines.get(i); String signatureValue = chunkMetadata.substring(chunkMetadata.indexOf(SIGNATURE_KEY) + SIGNATURE_KEY.length()); assertThat(signatureValue.length()).isEqualTo(SIGV4_CHUNK_SIGNATURE_LENGTH); } } }
1,666
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer/internal/Aws4SignerPathNormalizationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.signer.internal; import static org.junit.Assert.assertEquals; import java.util.Arrays; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import software.amazon.awssdk.auth.signer.internal.AbstractAws4Signer.CanonicalRequest; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.utils.ToString; /** * Tests how canonical resource paths are created including normalization */ public class Aws4SignerPathNormalizationTest { public static Iterable<TestCase> data() { return Arrays.asList( // Handling slash tc("Empty path -> (initial) slash added", "", "/"), tc("Slash -> unchanged", "/", "/"), tc("Single segment with initial slash -> unchanged", "/foo", "/foo"), tc("Single segment no slash -> slash prepended", "foo", "/foo"), tc("Multiple segments -> unchanged", "/foo/bar", "/foo/bar"), tc("Multiple segments with trailing slash -> unchanged", "/foo/bar/", "/foo/bar/"), // Double URL encoding tc("Multiple segments, urlEncoded slash -> encodes percent", "/foo%2Fbar", "/foo%252Fbar", true, true), // No double-url-encoding + normalization tc("Single segment, dot -> should remove dot", "/.", "/"), tc("Single segment, double dot -> unchanged", "/..", "/.."), tc("Multiple segments with dot -> should remove dot", "/foo/./bar", "/foo/bar"), tc("Multiple segments with ending dot -> should remove dot and trailing slash", "/foo/bar/.", "/foo/bar"), tc("Multiple segments with dots -> should remove dots and preceding segment", "/foo/bar/../baz", "/foo/baz"), tc("First segment has colon -> unchanged, url encoded first", "foo:/bar", "/foo%3A/bar", true, true), // Double-url-encoding + normalization tc("Multiple segments, urlEncoded slash -> encodes percent", "/foo%2F.%2Fbar", "/foo%252F.%252Fbar", true, true), // Double-url-encoding + no normalization tc("No url encode, Multiple segments with dot -> unchanged", "/foo/./bar", "/foo/./bar", false, false), tc("Multiple segments with dots -> unchanged", "/foo/bar/../baz", "/foo/bar/../baz", false, false) ); } @ParameterizedTest @MethodSource("data") public void verifyNormalizedPath(TestCase tc) { String canonicalRequest = tc.canonicalRequest.string(); String[] requestParts = canonicalRequest.split("\\n"); String canonicalPath = requestParts[1]; assertEquals(tc.expectedPath, canonicalPath); } private static TestCase tc(String name, String path, String expectedPath) { return new TestCase(name, path, expectedPath, false, true); } private static TestCase tc(String name, String path, String expectedPath, boolean urlEncode, boolean normalizePath) { return new TestCase(name, path, expectedPath, urlEncode, normalizePath); } private static class TestCase { private String name; private String path; private String expectedPath; private CanonicalRequest canonicalRequest; public TestCase(String name, String path, String expectedPath, boolean urlEncode, boolean normalizePath) { SdkHttpFullRequest request = SdkHttpFullRequest.builder() .protocol("https") .host("localhost") .encodedPath(path) .method(SdkHttpMethod.PUT) .build(); this.name = name; this.path = path; this.expectedPath = expectedPath; this.canonicalRequest = new CanonicalRequest(request, request.toBuilder(), "sha-256", urlEncode, normalizePath); } @Override public String toString() { return ToString.builder("TestCase") .add("name", name) .add("path", path) .add("expectedPath", expectedPath) .build(); } } }
1,667
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer/internal/ContentChecksumTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.signer.internal; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; class ContentChecksumTest { @Test void equals_hashcode() { EqualsVerifier.forClass(ContentChecksum.class) .usingGetClass() .verify(); } }
1,668
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer/internal/SignerTestUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.signer.internal; import java.time.Clock; import java.time.Instant; import software.amazon.awssdk.auth.credentials.AwsCredentials; import software.amazon.awssdk.auth.signer.params.Aws4PresignerParams; import software.amazon.awssdk.auth.signer.params.Aws4SignerParams; import software.amazon.awssdk.auth.signer.params.SignerChecksumParams; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.regions.Region; public class SignerTestUtils { public static SdkHttpFullRequest signRequest(BaseAws4Signer signer, SdkHttpFullRequest request, AwsCredentials credentials, String signingName, Clock signingDateOverride, String region) { Aws4SignerParams signerParams = Aws4SignerParams.builder() .awsCredentials(credentials) .signingName(signingName) .signingClockOverride(signingDateOverride) .signingRegion(Region.of(region)) .build(); return signer.sign(request, signerParams); } public static SdkHttpFullRequest signRequest(BaseAws4Signer signer, SdkHttpFullRequest request, AwsCredentials credentials, String signingName, Clock signingDateOverride, String region, SignerChecksumParams signerChecksumParams) { Aws4SignerParams signerParams = Aws4SignerParams.builder() .awsCredentials(credentials) .signingName(signingName) .signingClockOverride(signingDateOverride) .signingRegion(Region.of(region)) .checksumParams(signerChecksumParams) .build(); return signer.sign(request, signerParams); } public static AsyncRequestBody signAsyncRequest(BaseAsyncAws4Signer signer, SdkHttpFullRequest request, AsyncRequestBody asyncRequestBody, AwsCredentials credentials, String signingName, Clock signingDateOverride, String region) { Aws4SignerParams signerParams = Aws4SignerParams.builder() .awsCredentials(credentials) .signingName(signingName) .signingClockOverride(signingDateOverride) .signingRegion(Region.of(region)) .build(); final Aws4SignerRequestParams requestParams = new Aws4SignerRequestParams(signerParams); return signer.signAsync(request, asyncRequestBody, requestParams, signerParams); } public static SdkHttpFullRequest presignRequest(BaseAws4Signer presigner, SdkHttpFullRequest request, AwsCredentials credentials, Instant expiration, String signingName, Clock signingDateOverride, String region) { Aws4PresignerParams signerParams = Aws4PresignerParams.builder() .awsCredentials(credentials) .expirationTime(expiration) .signingName(signingName) .signingClockOverride(signingDateOverride) .signingRegion(Region.of(region)) .build(); return presigner.presign(request, signerParams); } }
1,669
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer/internal/BaseEventStreamAsyncAws4SignerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.signer.internal; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.Map; import java.util.Random; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import software.amazon.awssdk.utils.BinaryUtils; import software.amazon.eventstream.HeaderValue; import software.amazon.eventstream.Message; public class BaseEventStreamAsyncAws4SignerTest { private static Map<String, HeaderValue> headers; @BeforeAll public static void setup() { headers = new LinkedHashMap<>(); headers.put("header1", HeaderValue.fromInteger(42)); headers.put("header2", HeaderValue.fromBoolean(false)); headers.put("header3", HeaderValue.fromString("Hello world")); } @Test public void toDebugString_emptyPayload_generatesCorrectString() { Message m = new Message(headers, new byte[0]); assertThat(BaseEventStreamAsyncAws4Signer.toDebugString(m, false)) .isEqualTo("Message = {headers={header1={42}, header2={false}, header3={\"Hello world\"}}, payload=}"); } @Test public void toDebugString_noHeaders_emptyPayload_generatesCorrectString() { Message m = new Message(new LinkedHashMap<>(), new byte[0]); assertThat(BaseEventStreamAsyncAws4Signer.toDebugString(m, false)) .isEqualTo("Message = {headers={}, payload=}"); } @Test public void toDebugString_largePayload_truncate_generatesCorrectString() { byte[] payload = new byte[128]; new Random().nextBytes(payload); Message m = new Message(headers, payload); byte[] first32 = Arrays.copyOf(payload, 32); String expectedPayloadString = BinaryUtils.toHex(first32); assertThat(BaseEventStreamAsyncAws4Signer.toDebugString(m, true)) .isEqualTo("Message = {headers={header1={42}, header2={false}, header3={\"Hello world\"}}, payload=" + expectedPayloadString + "...}"); } @Test public void toDebugString_largePayload_noTruncate_generatesCorrectString() { byte[] payload = new byte[128]; new Random().nextBytes(payload); Message m = new Message(headers, payload); String expectedPayloadString = BinaryUtils.toHex(payload); assertThat(BaseEventStreamAsyncAws4Signer.toDebugString(m, false)) .isEqualTo("Message = {headers={header1={42}, header2={false}, header3={\"Hello world\"}}, payload=" + expectedPayloadString + "}"); } @Test public void toDebugString_smallPayload_truncate_doesNotAddEllipsis() { byte[] payload = new byte[8]; new Random().nextBytes(payload); Message m = new Message(headers, payload); String expectedPayloadString = BinaryUtils.toHex(payload); assertThat(BaseEventStreamAsyncAws4Signer.toDebugString(m, true)) .isEqualTo("Message = {headers={header1={42}, header2={false}, header3={\"Hello world\"}}, payload=" + expectedPayloadString + "}"); } }
1,670
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer/internal/DigestComputingSubscriberTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.signer.internal; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import io.reactivex.Flowable; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import org.junit.jupiter.api.Test; import org.reactivestreams.Subscription; import software.amazon.awssdk.core.checksums.Algorithm; import software.amazon.awssdk.core.checksums.SdkChecksum; import software.amazon.awssdk.utils.BinaryUtils; public class DigestComputingSubscriberTest { @Test public void test_computesCorrectSha256() { String testString = "AWS SDK for Java"; String expectedDigest = "004c6bbd87e7fe70109b3bc23c8b1ab8f18a8bede0ed38c9233f6cdfd4f7b5d6"; DigestComputingSubscriber subscriber = DigestComputingSubscriber.forSha256(); Flowable<ByteBuffer> publisher = Flowable.just(ByteBuffer.wrap(testString.getBytes(StandardCharsets.UTF_8))); publisher.subscribe(subscriber); String computedDigest = BinaryUtils.toHex(subscriber.digestBytes().join()); assertThat(computedDigest).isEqualTo(expectedDigest); } @Test public void test_futureCancelledBeforeSubscribe_cancelsSubscription() { Subscription mockSubscription = mock(Subscription.class); DigestComputingSubscriber subscriber = DigestComputingSubscriber.forSha256(); subscriber.digestBytes().cancel(true); subscriber.onSubscribe(mockSubscription); verify(mockSubscription).cancel(); verify(mockSubscription, times(0)).request(anyLong()); } @Test public void test_publisherCallsOnError_errorPropagatedToFuture() { Subscription mockSubscription = mock(Subscription.class); DigestComputingSubscriber subscriber = DigestComputingSubscriber.forSha256(); subscriber.onSubscribe(mockSubscription); RuntimeException error = new RuntimeException("error"); subscriber.onError(error); assertThatThrownBy(subscriber.digestBytes()::join).hasCause(error); } @Test void test_computesCorrectSdkChecksum() { String testString = "Hello world"; String expectedDigest = "64ec88ca00b268e5ba1a35678a1b5316d212f4f366b2477232534a8aeca37f3c"; String expectedChecksum = "e1AsOh9IyGCa4hLN+2Od7jlnP14="; final SdkChecksum sdkChecksum = SdkChecksum.forAlgorithm(Algorithm.SHA1); DigestComputingSubscriber subscriber = DigestComputingSubscriber.forSha256(sdkChecksum); Flowable<ByteBuffer> publisher = Flowable.just(ByteBuffer.wrap(testString.getBytes(StandardCharsets.UTF_8))); publisher.subscribe(subscriber); String computedDigest = BinaryUtils.toHex(subscriber.digestBytes().join()); assertThat(computedDigest).isEqualTo(expectedDigest); assertThat(BinaryUtils.toBase64(sdkChecksum.getChecksumBytes())).isEqualTo(expectedChecksum); } }
1,671
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer/internal/ChunkedEncodingFunctionalTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.signer.internal; import static org.assertj.core.api.Assertions.assertThat; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.signer.internal.chunkedencoding.AwsS3V4ChunkSigner; import software.amazon.awssdk.auth.signer.internal.chunkedencoding.AwsSignedChunkedEncodingInputStream; import software.amazon.awssdk.core.internal.chunked.AwsChunkedEncodingConfig; import software.amazon.awssdk.utils.BinaryUtils; /** * Functional tests for the AwsChunkedEncodingInputStream using Sigv4 for chunk signing. */ public class ChunkedEncodingFunctionalTest { private static final byte[] SIGNATURE = "signature".getBytes(StandardCharsets.UTF_8); private static final byte[] SIGNING_KEY = "signingkey".getBytes(StandardCharsets.UTF_8); private static final String DATE_TIME = "20201216T011309Z"; private static final String SCOPE = "20201216/us-west-2/s3/aws4_request"; private static final String CRLF = "\r\n"; private static final int DEFAULT_CHUNK_SIZE = 128 * 1024; @Test public void chunkedEncodingStream_smallObject_createsCorrectChunks() throws IOException { String chunkData = "helloworld"; String expectedChunkOutput = "a;chunk-signature=a0c7e7324d9c209c4a86a1c1452d60862591b7370a725364d52ba490210f2d9d" + CRLF + "helloworld" + CRLF + "0;chunk-signature=4722d8dac986015bdabeb5fafcb45db7b5585329befa485849c4938fed2aaaa2" + CRLF + CRLF; ByteArrayInputStream input = new ByteArrayInputStream(chunkData.getBytes()); AwsSignedChunkedEncodingInputStream stream = createChunkedEncodingInputStream(input); verifySignedPayload(expectedChunkOutput, stream); } @Test public void chunkedEncodingStream_largeObject_createsCorrectChunks() throws IOException { String chunk1Data = StringUtils.repeat('a', DEFAULT_CHUNK_SIZE); String chunk2Data = "a"; String expectedChunkOutput = "20000;chunk-signature=be3155d539d4f5daf575096ab6d7090070b5ad00be6b802a8eb4c8bacd6e7dcb" + CRLF + chunk1Data + CRLF + "1;chunk-signature=0362eef10ceccf47fc1bf944a9df45a3e7dd5ea936e118b00e3d649b1d825f2f" + CRLF + chunk2Data + CRLF + "0;chunk-signature=3d5a2da1f773f64fdde2c6ca7d18c4bfee2a5a76b8153854c2a722c3fe8549cc" + CRLF + CRLF; ByteArrayInputStream input = new ByteArrayInputStream(chunk1Data.concat(chunk2Data).getBytes()); AwsSignedChunkedEncodingInputStream stream = createChunkedEncodingInputStream(input); verifySignedPayload(expectedChunkOutput, stream); } @Test public void chunkedEncodingStream_emptyString_createsCorrectChunks() throws IOException { String chunkData = ""; String expectedChunkOutput = "0;chunk-signature=67a2a80cee05190f0376fa861594fcfa351606cfdcf932b45781ddd6e4d78501" + CRLF + CRLF; ByteArrayInputStream input = new ByteArrayInputStream(chunkData.getBytes()); AwsSignedChunkedEncodingInputStream stream = createChunkedEncodingInputStream(input); verifySignedPayload(expectedChunkOutput, stream); } private void verifySignedPayload(String expectedChunkOutput, AwsSignedChunkedEncodingInputStream stream) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); IOUtils.copy(stream, output); String result = new String(output.toByteArray(), StandardCharsets.UTF_8); assertThat(result).isEqualTo(expectedChunkOutput); } private AwsSignedChunkedEncodingInputStream createChunkedEncodingInputStream(ByteArrayInputStream input) { AwsS3V4ChunkSigner chunkSigner = new AwsS3V4ChunkSigner(SIGNING_KEY, DATE_TIME, SCOPE); String signatureHex = BinaryUtils.toHex(SIGNATURE); return AwsSignedChunkedEncodingInputStream.builder().inputStream(input) .headerSignature(signatureHex).awsChunkSigner(chunkSigner) .awsChunkedEncodingConfig(AwsChunkedEncodingConfig.create()).build(); } }
1,672
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer/internal/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.auth.signer.internal; 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(); } }
1,673
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer/internal/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.auth.signer.internal; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import org.junit.Test; public class FifoCacheTest { @Test public void test() { FifoCache<String> cache = new FifoCache<String>(3); assertTrue(cache.size() == 0); cache.add("k1", "v1"); assertTrue(cache.size() == 1); cache.add("k1", "v11"); assertTrue(cache.size() == 1); cache.add("k2", "v2"); assertTrue(cache.size() == 2); cache.add("k3", "v3"); assertTrue(cache.size() == 3); assertEquals("v11", cache.get("k1")); assertEquals("v2", cache.get("k2")); assertEquals("v3", cache.get("k3")); cache.add("k4", "v4"); assertTrue(cache.size() == 3); assertNull(cache.get("k1")); } @Test(expected = IllegalArgumentException.class) public void testZeroSize() { new FifoCache<Object>(0); } @Test(expected = IllegalArgumentException.class) public void testIllegalArgument() { new FifoCache<Object>(-1); } @Test public void testSingleEntry() { FifoCache<String> cache = new FifoCache<String>(1); assertTrue(cache.size() == 0); cache.add("k1", "v1"); assertTrue(cache.size() == 1); cache.add("k1", "v11"); assertTrue(cache.size() == 1); assertEquals("v11", cache.get("k1")); cache.add("k2", "v2"); assertTrue(cache.size() == 1); assertEquals("v2", cache.get("k2")); assertNull(cache.get("k1")); cache.add("k3", "v3"); assertTrue(cache.size() == 1); assertEquals("v3", cache.get("k3")); assertNull(cache.get("k2")); } }
1,674
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/DefaultCredentialsProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.credentials; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import java.util.Arrays; import java.util.List; import java.util.function.Supplier; import org.junit.jupiter.api.Test; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileFileSupplier; import software.amazon.awssdk.utils.StringInputStream; class DefaultCredentialsProviderTest { @Test void resolveCredentials_ProfileCredentialsProviderWithProfileFile_returnsCredentials() { DefaultCredentialsProvider provider = DefaultCredentialsProvider .builder() .profileFile(credentialFile("test", "access", "secret")) .profileName("test") .build(); assertThat(provider.resolveCredentials()).satisfies(awsCredentials -> { assertThat(awsCredentials.accessKeyId()).isEqualTo("access"); assertThat(awsCredentials.secretAccessKey()).isEqualTo("secret"); }); } @Test void resolveCredentials_ProfileCredentialsProviderWithProfileFileSupplier_resolvesCredentialsPerCall() { List<ProfileFile> profileFileList = Arrays.asList(credentialFile("test", "access", "secret"), credentialFile("test", "modified", "update")); ProfileFileSupplier profileFileSupplier = supply(profileFileList); DefaultCredentialsProvider provider = DefaultCredentialsProvider .builder() .profileFile(profileFileSupplier) .profileName("test") .build(); assertThat(provider.resolveCredentials()).satisfies(awsCredentials -> { assertThat(awsCredentials.accessKeyId()).isEqualTo("access"); assertThat(awsCredentials.secretAccessKey()).isEqualTo("secret"); }); assertThat(provider.resolveCredentials()).satisfies(awsCredentials -> { assertThat(awsCredentials.accessKeyId()).isEqualTo("modified"); assertThat(awsCredentials.secretAccessKey()).isEqualTo("update"); }); } @Test void resolveCredentials_ProfileCredentialsProviderWithProfileFileSupplier_returnsCredentials() { ProfileFile profileFile = credentialFile("test", "access", "secret"); ProfileFileSupplier profileFileSupplier = ProfileFileSupplier.fixedProfileFile(profileFile); DefaultCredentialsProvider provider = DefaultCredentialsProvider .builder() .profileFile(profileFileSupplier) .profileName("test") .build(); assertThat(provider.resolveCredentials()).satisfies(awsCredentials -> { assertThat(awsCredentials.accessKeyId()).isEqualTo("access"); assertThat(awsCredentials.secretAccessKey()).isEqualTo("secret"); }); } @Test void resolveCredentials_ProfileCredentialsProviderWithSupplierProfileFile_returnsCredentials() { Supplier<ProfileFile> supplier = () -> credentialFile("test", "access", "secret"); DefaultCredentialsProvider provider = DefaultCredentialsProvider .builder() .profileFile(supplier) .profileName("test") .build(); assertThat(provider.resolveCredentials()).satisfies(awsCredentials -> { assertThat(awsCredentials.accessKeyId()).isEqualTo("access"); assertThat(awsCredentials.secretAccessKey()).isEqualTo("secret"); }); } private ProfileFile credentialFile(String credentialFile) { return ProfileFile.builder() .content(new StringInputStream(credentialFile)) .type(ProfileFile.Type.CREDENTIALS) .build(); } private ProfileFile credentialFile(String name, String accessKeyId, String secretAccessKey) { String contents = String.format("[%s]\naws_access_key_id = %s\naws_secret_access_key = %s\n", name, accessKeyId, secretAccessKey); return credentialFile(contents); } private static ProfileFileSupplier supply(Iterable<ProfileFile> iterable) { return iterable.iterator()::next; } }
1,675
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/EC2MetadataServiceMock.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.credentials; import static software.amazon.awssdk.core.SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.List; import org.apache.commons.io.IOUtils; import software.amazon.awssdk.auth.signer.internal.SignerTestUtils; import software.amazon.awssdk.utils.StringUtils; /** * Mock server for imitating the Amazon EC2 Instance Metadata Service. Tests can * use this class to start up a server on a localhost port, and control what * response the server will send when a connection is made. */ //TODO: this should really be replaced by WireMock public class EC2MetadataServiceMock { private static final String OUTPUT_HEADERS = "HTTP/1.1 200 OK\r\n" + "Content-Type: text/html\r\n" + "Content-Length: "; private static final String OUTPUT_END_OF_HEADERS = "\r\n\r\n"; private final String securityCredentialsResource; private EC2MockMetadataServiceListenerThread hosmMockServerThread; public EC2MetadataServiceMock(String securityCredentialsResource) { this.securityCredentialsResource = securityCredentialsResource; } /** * Sets the name of the file that should be sent back as the response from * this mock server. The files are loaded from the software/amazon/awssdk/auth * directory of the tst folder, and no file extension should be specified. * * @param responseFileName The name of the file that should be sent back as the response * from this mock server. */ public void setResponseFileName(String responseFileName) { hosmMockServerThread.setResponseFileName(responseFileName); } /** * Accepts a newline delimited list of security credential names that the * mock metadata service should advertise as available. * * @param securityCredentialNames A newline delimited list of security credentials that the * metadata service will advertise as available. */ public void setAvailableSecurityCredentials(String securityCredentialNames) { hosmMockServerThread.setAvailableSecurityCredentials(securityCredentialNames); } public void start() throws IOException { hosmMockServerThread = new EC2MockMetadataServiceListenerThread(startServerSocket(), securityCredentialsResource); hosmMockServerThread.start(); } public void stop() { hosmMockServerThread.stopServer(); } private ServerSocket startServerSocket() { try { ServerSocket serverSocket = new ServerSocket(0); System.setProperty(AWS_EC2_METADATA_SERVICE_ENDPOINT.property(), "http://localhost:" + serverSocket.getLocalPort()); System.out.println("Started mock metadata service at: " + System.getProperty(AWS_EC2_METADATA_SERVICE_ENDPOINT.property())); return serverSocket; } catch (IOException ioe) { throw new RuntimeException("Unable to start mock EC2 metadata server", ioe); } } /** * Thread subclass that listens for connections on an opened server socket * and response with a predefined response file. */ private static class EC2MockMetadataServiceListenerThread extends Thread { private static final String TOKEN_RESOURCE_PATH = "/latest/api/token"; private ServerSocket serverSocket; private final String credentialsResource; private String responseFileName; private String securityCredentialNames; public EC2MockMetadataServiceListenerThread(ServerSocket serverSocket, String credentialsResource) { this.serverSocket = serverSocket; this.credentialsResource = credentialsResource; } public void setResponseFileName(String responseFileName) { this.responseFileName = responseFileName; } public void setAvailableSecurityCredentials(String securityCredentialNames) { this.securityCredentialNames = securityCredentialNames; } @Override public void run() { while (true) { Socket socket = null; try { socket = serverSocket.accept(); } catch (IOException e) { // Just exit if the socket gets shut down while we're waiting return; } try (OutputStream outputStream = socket.getOutputStream()) { InputStream inputStream = socket.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String requestLine = reader.readLine(); String[] strings = requestLine.split(" "); String resourcePath = strings[1]; String httpResponse = null; if (resourcePath.equals(credentialsResource)) { httpResponse = formHttpResponse(securityCredentialNames); outputStream.write(httpResponse.getBytes()); } else if (resourcePath.startsWith(credentialsResource)) { String responseFilePath = "/software/amazon/awssdk/core/auth/" + responseFileName + ".json"; System.out.println("Serving: " + responseFilePath); List<String> dataFromFile; StringBuilder credentialsString; try (InputStream responseFileInputStream = this.getClass().getResourceAsStream(responseFilePath)) { dataFromFile = IOUtils.readLines(responseFileInputStream); } credentialsString = new StringBuilder(); for (String line : dataFromFile) { credentialsString.append(line); } httpResponse = formHttpResponse(credentialsString .toString()); outputStream.write(httpResponse.getBytes()); } else if (TOKEN_RESOURCE_PATH.equals(resourcePath)) { httpResponse = "HTTP/1.1 404 Not Found\r\n" + "Content-Length: 0\r\n" + "\r\n"; outputStream.write(httpResponse.getBytes()); } else { throw new RuntimeException("Unknown resource requested: " + resourcePath); } } catch (IOException e) { throw new RuntimeException("Unable to respond to request", e); } finally { try { socket.close(); } catch (Exception e) { // Ignored or expected. } } } } private String formHttpResponse(String content) { return OUTPUT_HEADERS + content.length() + OUTPUT_END_OF_HEADERS + content; } public void stopServer() { if (serverSocket != null) { try { serverSocket.close(); } catch (IOException e) { throw new RuntimeException("Unable to stop server", e); } } } } }
1,676
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/CredentialsEndpointRetryParametersTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.credentials; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import org.junit.jupiter.api.Test; import software.amazon.awssdk.regions.util.ResourcesEndpointRetryParameters; /** * Unit tests for {@link ResourcesEndpointRetryParameters}. */ public class CredentialsEndpointRetryParametersTest { @Test public void defaultParams() { ResourcesEndpointRetryParameters params = ResourcesEndpointRetryParameters.builder().build(); assertNull(params.getStatusCode()); assertNull(params.getException()); } @Test public void defaultParams_withStatusCode() { Integer statusCode = new Integer(400); ResourcesEndpointRetryParameters params = ResourcesEndpointRetryParameters.builder() .withStatusCode(statusCode) .build(); assertEquals(statusCode, params.getStatusCode()); assertNull(params.getException()); } @Test public void defaultParams_withStatusCodeAndException() { Integer statusCode = new Integer(500); ResourcesEndpointRetryParameters params = ResourcesEndpointRetryParameters.builder() .withStatusCode(statusCode) .withException(new IOException()) .build(); assertEquals(statusCode, params.getStatusCode()); assertTrue(params.getException() instanceof IOException); } }
1,677
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/NoopTestRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.credentials; import java.util.Collections; import java.util.List; import java.util.Optional; import software.amazon.awssdk.core.RequestOverrideConfiguration; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.SdkRequest; public class NoopTestRequest extends SdkRequest { private NoopTestRequest() { } @Override public Optional<? extends RequestOverrideConfiguration> overrideConfiguration() { return Optional.empty(); } @Override public Builder toBuilder() { return new BuilderImpl(); } public static Builder builder() { return new BuilderImpl(); } @Override public List<SdkField<?>> sdkFields() { return Collections.emptyList(); } public interface Builder extends SdkRequest.Builder { @Override NoopTestRequest build(); } private static class BuilderImpl implements SdkRequest.Builder, Builder { @Override public RequestOverrideConfiguration overrideConfiguration() { return null; } @Override public NoopTestRequest build() { return new NoopTestRequest(); } } }
1,678
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/ContainerCredentialsProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.credentials; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static software.amazon.awssdk.core.SdkSystemSetting.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.net.URI; import org.apache.commons.lang.exception.ExceptionUtils; import org.junit.AfterClass; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.util.SdkUserAgent; import software.amazon.awssdk.regions.util.ResourcesEndpointProvider; import software.amazon.awssdk.testutils.EnvironmentVariableHelper; /** * Tests for the {@link ContainerCredentialsProviderTest}. */ public class ContainerCredentialsProviderTest { @ClassRule public static WireMockRule mockServer = new WireMockRule(0); /** Environment variable name for the AWS ECS Container credentials path. */ private static final String CREDENTIALS_PATH = "/dummy/credentials/path"; private static final String ACCESS_KEY_ID = "ACCESS_KEY_ID"; private static final String SECRET_ACCESS_KEY = "SECRET_ACCESS_KEY"; private static final String TOKEN = "TOKEN_TOKEN_TOKEN"; private ContainerCredentialsProvider credentialsProvider; private static EnvironmentVariableHelper helper = new EnvironmentVariableHelper(); @Before public void setup() { credentialsProvider = ContainerCredentialsProvider.builder() .endpoint("http://localhost:" + mockServer.port()) .build(); helper.set(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI, CREDENTIALS_PATH); } @AfterClass public static void tearDown() { helper.reset(); } /** * Tests that when "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" is not set, throws exception. */ @Test(expected = SdkClientException.class) public void testEnvVariableNotSet() { helper.remove(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI); ContainerCredentialsProvider.builder() .build() .resolveCredentials(); } /** * Tests that the getCredentials returns a value when it receives a valid 200 response from endpoint. */ @Test public void testGetCredentialsReturnsValidResponseFromEcsEndpoint() { stubForSuccessResponse(); AwsSessionCredentials credentials = (AwsSessionCredentials) credentialsProvider.resolveCredentials(); assertThat(credentials).isNotNull(); assertThat(credentials.accessKeyId()).isEqualTo(ACCESS_KEY_ID); assertThat(credentials.secretAccessKey()).isEqualTo(SECRET_ACCESS_KEY); assertThat(credentials.sessionToken()).isEqualTo(TOKEN); } /** * Tests that the getCredentials won't leak credentials data if the response from ECS is corrupted. */ @Test public void getCredentialsWithCorruptResponseDoesNotIncludeCredentialsInExceptionMessage() { stubForCorruptedSuccessResponse(); assertThatThrownBy(credentialsProvider::resolveCredentials).satisfies(t -> { String stackTrace = ExceptionUtils.getStackTrace(t); assertThat(stackTrace).doesNotContain("ACCESS_KEY_ID"); assertThat(stackTrace).doesNotContain("SECRET_ACCESS_KEY"); assertThat(stackTrace).doesNotContain("TOKEN_TOKEN_TOKEN"); }); } private void stubForSuccessResponse() { stubFor200Response(getSuccessfulBody()); } private void stubForCorruptedSuccessResponse() { String body = getSuccessfulBody(); stubFor200Response(body.substring(0, body.length() - 2)); } private void stubFor200Response(String body) { stubFor(get(urlPathEqualTo(CREDENTIALS_PATH)) .withHeader("User-Agent", equalTo(SdkUserAgent.create().userAgent())) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withHeader("charset", "utf-8") .withBody(body))); } private String getSuccessfulBody() { return "{\"AccessKeyId\":\"ACCESS_KEY_ID\"," + "\"SecretAccessKey\":\"SECRET_ACCESS_KEY\"," + "\"Token\":\"TOKEN_TOKEN_TOKEN\"," + "\"Expiration\":\"3000-05-03T04:55:54Z\"}"; } /** * Dummy CredentialsPathProvider that overrides the endpoint and connects to the WireMock server. */ private static class TestCredentialsEndpointProvider implements ResourcesEndpointProvider { private final String host; public TestCredentialsEndpointProvider(String host) { this.host = host; } @Override public URI endpoint() { return invokeSafely(() -> new URI(host + CREDENTIALS_PATH)); } } }
1,679
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/HttpCredentialsLoaderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.credentials; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.time.Duration; import java.time.Instant; import java.util.Date; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import software.amazon.awssdk.auth.credentials.internal.HttpCredentialsLoader; import software.amazon.awssdk.auth.credentials.internal.StaticResourcesEndpointProvider; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.util.SdkUserAgent; import software.amazon.awssdk.regions.util.ResourcesEndpointProvider; import software.amazon.awssdk.utils.DateUtils; import software.amazon.awssdk.utils.IoUtils; public class HttpCredentialsLoaderTest { @ClassRule public static WireMockRule mockServer = new WireMockRule(0); /** One minute (in milliseconds) */ private static final long ONE_MINUTE = 1000L * 60; /** Environment variable name for the AWS ECS Container credentials path. */ private static final String CREDENTIALS_PATH = "/dummy/credentials/path"; private static String successResponse; private static String successResponseWithInvalidBody; @BeforeClass public static void setup() throws IOException { try (InputStream successInputStream = HttpCredentialsLoaderTest.class.getResourceAsStream ("/resources/wiremock/successResponse.json"); InputStream responseWithInvalidBodyInputStream = HttpCredentialsLoaderTest.class.getResourceAsStream ("/resources/wiremock/successResponseWithInvalidBody.json")) { successResponse = IoUtils.toUtf8String(successInputStream); successResponseWithInvalidBody = IoUtils.toUtf8String(responseWithInvalidBodyInputStream); } } /** * Test that loadCredentials returns proper credentials when response from client is in proper Json format. */ @Test public void testLoadCredentialsParsesJsonResponseProperly() { stubForSuccessResponseWithCustomBody(successResponse); HttpCredentialsLoader credentialsProvider = HttpCredentialsLoader.create(); AwsSessionCredentials credentials = (AwsSessionCredentials) credentialsProvider.loadCredentials(testEndpointProvider()) .getAwsCredentials(); assertThat(credentials.accessKeyId()).isEqualTo("ACCESS_KEY_ID"); assertThat(credentials.secretAccessKey()).isEqualTo("SECRET_ACCESS_KEY"); assertThat(credentials.sessionToken()).isEqualTo("TOKEN_TOKEN_TOKEN"); } /** * Test that when credentials are null and response from client does not have access key/secret key, * throws RuntimeException. */ @Test public void testLoadCredentialsThrowsAceWhenClientResponseDontHaveKeys() { // Stub for success response but without keys in the response body stubForSuccessResponseWithCustomBody(successResponseWithInvalidBody); HttpCredentialsLoader credentialsProvider = HttpCredentialsLoader.create(); assertThatExceptionOfType(SdkClientException.class).isThrownBy(() -> credentialsProvider.loadCredentials(testEndpointProvider())) .withMessage("Failed to load credentials from metadata service."); } /** * Tests how the credentials provider behaves when the * server is not running. */ @Test public void testNoMetadataService() throws Exception { stubForErrorResponse(); HttpCredentialsLoader credentialsProvider = HttpCredentialsLoader.create(); // When there are no credentials, the provider should throw an exception if we can't connect assertThatExceptionOfType(SdkClientException.class).isThrownBy(() -> credentialsProvider.loadCredentials(testEndpointProvider())); // When there are valid credentials (but need to be refreshed) and the endpoint returns 404 status, // the provider should throw an exception. stubForSuccessResonseWithCustomExpirationDate(new Date(System.currentTimeMillis() + ONE_MINUTE * 4)); credentialsProvider.loadCredentials(testEndpointProvider()); // loads the credentials that will be expired soon stubForErrorResponse(); // Behaves as if server is unavailable. assertThatExceptionOfType(SdkClientException.class).isThrownBy(() -> credentialsProvider.loadCredentials(testEndpointProvider())); } private void stubForSuccessResponseWithCustomBody(String body) { stubFor( get(urlPathEqualTo(CREDENTIALS_PATH)) .withHeader("User-Agent", equalTo(SdkUserAgent.create().userAgent())) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withHeader("charset", "utf-8") .withBody(body))); } private void stubForSuccessResonseWithCustomExpirationDate(Date expiration) { stubForSuccessResponseWithCustomBody("{\"AccessKeyId\":\"ACCESS_KEY_ID\",\"SecretAccessKey\":\"SECRET_ACCESS_KEY\"," + "\"Expiration\":\"" + DateUtils.formatIso8601Date(expiration.toInstant()) + "\"}"); } private void stubForErrorResponse() { stubFor( get(urlPathEqualTo(CREDENTIALS_PATH)) .willReturn(aResponse() .withStatus(404) .withHeader("Content-Type", "application/json") .withHeader("charset", "utf-8") .withBody("{\"code\":\"404 Not Found\",\"message\":\"DetailedErrorMessage\"}"))); } private ResourcesEndpointProvider testEndpointProvider() { return new StaticResourcesEndpointProvider(URI.create("http://localhost:" + mockServer.port() + CREDENTIALS_PATH), null); } }
1,680
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/ContainerCredentialsRetryPolicyTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.credentials; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.credentials.internal.ContainerCredentialsRetryPolicy; import software.amazon.awssdk.regions.util.ResourcesEndpointRetryParameters; public class ContainerCredentialsRetryPolicyTest { private static ContainerCredentialsRetryPolicy retryPolicy; @BeforeAll public static void setup() { retryPolicy = new ContainerCredentialsRetryPolicy(); } @Test public void shouldRetry_ReturnsTrue_For5xxStatusCode() { assertTrue(retryPolicy.shouldRetry(1, ResourcesEndpointRetryParameters.builder().withStatusCode(501).build())); } @Test public void shouldRetry_ReturnsFalse_ForNon5xxStatusCode() { assertFalse(retryPolicy.shouldRetry(1, ResourcesEndpointRetryParameters.builder().withStatusCode(404).build())); assertFalse(retryPolicy.shouldRetry(1, ResourcesEndpointRetryParameters.builder().withStatusCode(300).build())); assertFalse(retryPolicy.shouldRetry(1, ResourcesEndpointRetryParameters.builder().withStatusCode(202).build())); } @Test public void shouldRetry_ReturnsTrue_ForIoException() { assertTrue(retryPolicy.shouldRetry(1, ResourcesEndpointRetryParameters.builder() .withException(new IOException()).build())); } @Test public void shouldRetry_ReturnsFalse_ForNonIoException() { assertFalse(retryPolicy.shouldRetry(1, ResourcesEndpointRetryParameters.builder() .withException(new RuntimeException()).build())); assertFalse(retryPolicy.shouldRetry(1, ResourcesEndpointRetryParameters.builder() .withException(new Exception()).build())); } @Test public void shouldRetry_ReturnsFalse_WhenMaxRetriesExceeded() { assertFalse(retryPolicy.shouldRetry(5, ResourcesEndpointRetryParameters.builder().withStatusCode(501).build())); } }
1,681
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/ProfileCredentialsProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.credentials; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.google.common.jimfs.Jimfs; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; import java.util.function.Supplier; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileFileSupplier; import software.amazon.awssdk.profiles.ProfileProperty; import software.amazon.awssdk.utils.StringInputStream; /** * Verify functionality of {@link ProfileCredentialsProvider}. */ public class ProfileCredentialsProviderTest { private static FileSystem jimfs; private static Path testDirectory; @BeforeAll public static void setup() { jimfs = Jimfs.newFileSystem(); testDirectory = jimfs.getPath("test"); } @AfterAll public static void tearDown() { try { jimfs.close(); } catch (IOException e) { // no-op } } @Test void missingCredentialsFileThrowsExceptionInResolveCredentials() { ProfileCredentialsProvider provider = new ProfileCredentialsProvider.BuilderImpl() .defaultProfileFileLoader(() -> { throw new IllegalStateException(); }) .build(); assertThatThrownBy(provider::resolveCredentials).isInstanceOf(IllegalStateException.class); } @Test void missingProfileFileThrowsExceptionInResolveCredentials() { ProfileCredentialsProvider provider = new ProfileCredentialsProvider.BuilderImpl() .defaultProfileFileLoader(() -> ProfileFile.builder() .content(new StringInputStream("")) .type(ProfileFile.Type.CONFIGURATION) .build()) .build(); assertThatThrownBy(provider::resolveCredentials).isInstanceOf(SdkClientException.class); } @Test void missingProfileThrowsExceptionInResolveCredentials() { ProfileFile file = profileFile("[default]\n" + "aws_access_key_id = defaultAccessKey\n" + "aws_secret_access_key = defaultSecretAccessKey"); ProfileCredentialsProvider provider = ProfileCredentialsProvider.builder().profileFile(file).profileName("foo").build(); assertThatThrownBy(provider::resolveCredentials).isInstanceOf(SdkClientException.class); } @Test void profileWithoutCredentialsThrowsExceptionInResolveCredentials() { ProfileFile file = profileFile("[default]"); ProfileCredentialsProvider provider = ProfileCredentialsProvider.builder().profileFile(file).profileName("default").build(); assertThatThrownBy(provider::resolveCredentials).isInstanceOf(SdkClientException.class); } @Test void presentProfileReturnsCredentials() { ProfileFile file = profileFile("[default]\n" + "aws_access_key_id = defaultAccessKey\n" + "aws_secret_access_key = defaultSecretAccessKey"); ProfileCredentialsProvider provider = ProfileCredentialsProvider.builder().profileFile(file).profileName("default").build(); assertThat(provider.resolveCredentials()).satisfies(credentials -> { assertThat(credentials.accessKeyId()).isEqualTo("defaultAccessKey"); assertThat(credentials.secretAccessKey()).isEqualTo("defaultSecretAccessKey"); }); } @Test void profileWithWebIdentityToken() { String token = "/User/home/test"; ProfileFile file = profileFile("[default]\n" + "aws_access_key_id = defaultAccessKey\n" + "aws_secret_access_key = defaultSecretAccessKey\n" + "web_identity_token_file = " + token); assertThat(file.profile("default").get().property(ProfileProperty.WEB_IDENTITY_TOKEN_FILE).get()).isEqualTo(token); } @Test void resolveCredentials_missingProfileFileCausesExceptionInMethod_throwsException() { ProfileCredentialsProvider.BuilderImpl builder = new ProfileCredentialsProvider.BuilderImpl(); builder.defaultProfileFileLoader(() -> ProfileFile.builder() .content(new StringInputStream("")) .type(ProfileFile.Type.CONFIGURATION) .build()); ProfileCredentialsProvider provider = builder.build(); assertThatThrownBy(provider::resolveCredentials).isInstanceOf(SdkClientException.class); } @Test void resolveCredentials_missingProfile_throwsException() { ProfileFile file = profileFile("[default]\n" + "aws_access_key_id = defaultAccessKey\n" + "aws_secret_access_key = defaultSecretAccessKey"); try (ProfileCredentialsProvider provider = ProfileCredentialsProvider.builder() .profileFile(() -> file) .profileName("foo") .build()) { assertThatThrownBy(provider::resolveCredentials).isInstanceOf(SdkClientException.class); } } @Test void resolveCredentials_profileWithoutCredentials_throwsException() { ProfileFile file = profileFile("[default]"); ProfileCredentialsProvider provider = ProfileCredentialsProvider.builder() .profileFile(() -> file) .profileName("default") .build(); assertThatThrownBy(provider::resolveCredentials).isInstanceOf(SdkClientException.class); } @Test void resolveCredentials_presentProfile_returnsCredentials() { ProfileFile file = profileFile("[default]\n" + "aws_access_key_id = defaultAccessKey\n" + "aws_secret_access_key = defaultSecretAccessKey"); ProfileCredentialsProvider provider = ProfileCredentialsProvider.builder() .profileFile(() -> file) .profileName("default") .build(); assertThat(provider.resolveCredentials()).satisfies(credentials -> { assertThat(credentials.accessKeyId()).isEqualTo("defaultAccessKey"); assertThat(credentials.secretAccessKey()).isEqualTo("defaultSecretAccessKey"); }); } @Test void resolveCredentials_presentProfileFileSupplier_returnsCredentials() { Path path = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey"); ProfileCredentialsProvider provider = ProfileCredentialsProvider.builder() .profileFile(ProfileFileSupplier.reloadWhenModified(path, ProfileFile.Type.CREDENTIALS)) .profileName("default") .build(); assertThat(provider.resolveCredentials()).satisfies(credentials -> { assertThat(credentials.accessKeyId()).isEqualTo("defaultAccessKey"); assertThat(credentials.secretAccessKey()).isEqualTo("defaultSecretAccessKey"); }); } @Test void resolveCredentials_presentSupplierProfileFile_returnsCredentials() { Supplier<ProfileFile> supplier = () -> profileFile("[default]\naws_access_key_id = defaultAccessKey\n" + "aws_secret_access_key = defaultSecretAccessKey\n"); ProfileCredentialsProvider provider = ProfileCredentialsProvider.builder() .profileFile(supplier) .profileName("default") .build(); assertThat(provider.resolveCredentials()).satisfies(credentials -> { assertThat(credentials.accessKeyId()).isEqualTo("defaultAccessKey"); assertThat(credentials.secretAccessKey()).isEqualTo("defaultSecretAccessKey"); }); } @Test void create_noProfileName_returnsProfileCredentialsProviderToResolveWithDefaults() { ProfileCredentialsProvider provider = ProfileCredentialsProvider.create(); String toString = provider.toString(); assertThat(toString).satisfies(s -> assertThat(s).contains("profileName=default")); } @Test void create_givenProfileName_returnsProfileCredentialsProviderToResolveForGivenName() { ProfileCredentialsProvider provider = ProfileCredentialsProvider.create("override"); String toString = provider.toString(); assertThat(toString).satisfies(s -> assertThat(s).contains("profileName=override")); } @Test void toString_anyProfileCredentialsProviderAfterResolvingCredentialsFileDoesExists_returnsProfileFile() { ProfileCredentialsProvider provider = new ProfileCredentialsProvider.BuilderImpl() .defaultProfileFileLoader(() -> profileFile("[default]\naws_access_key_id = not-set\n" + "aws_secret_access_key = not-set\n")) .build(); provider.resolveCredentials(); String toString = provider.toString(); assertThat(toString).satisfies(s -> { assertThat(s).contains("profileName=default"); assertThat(s).contains("profileFile="); }); } @Test void toString_anyProfileCredentialsProviderAfterResolvingCredentialsFileDoesNotExist_throwsException() { ProfileCredentialsProvider provider = new ProfileCredentialsProvider.BuilderImpl() .defaultProfileFileLoader(() -> ProfileFile.builder() .content(new StringInputStream("")) .type(ProfileFile.Type.CONFIGURATION) .build()) .build(); assertThatThrownBy(provider::resolveCredentials).isInstanceOf(SdkClientException.class); } @Test void toString_anyProfileCredentialsProviderBeforeResolvingCredentials_doesNotReturnProfileFile() { ProfileCredentialsProvider provider = new ProfileCredentialsProvider.BuilderImpl() .defaultProfileFileLoader(() -> ProfileFile.builder() .content(new StringInputStream("")) .type(ProfileFile.Type.CONFIGURATION) .build()) .build(); String toString = provider.toString(); assertThat(toString).satisfies(s -> { assertThat(s).contains("profileName"); assertThat(s).doesNotContain("profileFile"); }); } @Test void toBuilder_fromCredentialsProvider_returnsBuilderCapableOfProducingSimilarProvider() { ProfileCredentialsProvider provider1 = ProfileCredentialsProvider.create("override"); ProfileCredentialsProvider provider2 = provider1.toBuilder().build(); String provider1ToString = provider1.toString(); String provider2ToString = provider2.toString(); assertThat(provider1ToString).isEqualTo(provider2ToString); } private ProfileFile profileFile(String string) { return ProfileFile.builder().content(new StringInputStream(string)).type(ProfileFile.Type.CONFIGURATION).build(); } private Path generateTestFile(String contents, String filename) { try { Files.createDirectories(testDirectory); return Files.write(testDirectory.resolve(filename), contents.getBytes(StandardCharsets.UTF_8)); } catch (IOException e) { throw new RuntimeException(e); } } private Path generateTestCredentialsFile(String accessKeyId, String secretAccessKey) { String contents = String.format("[default]\naws_access_key_id = %s\naws_secret_access_key = %s\n", accessKeyId, secretAccessKey); return generateTestFile(contents, "credentials.txt"); } }
1,682
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/CredentialUtilsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.credentials; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.AwsSessionCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; public class CredentialUtilsTest { @Test public void isAnonymous_AwsCredentials_true() { assertThat(CredentialUtils.isAnonymous(AwsBasicCredentials.ANONYMOUS_CREDENTIALS)).isTrue(); } @Test public void isAnonymous_AwsCredentials_false() { assertThat(CredentialUtils.isAnonymous(AwsBasicCredentials.create("akid", "skid"))).isFalse(); } @Test public void isAnonymous_AwsCredentialsIdentity_true() { assertThat(CredentialUtils.isAnonymous((AwsCredentialsIdentity) AwsBasicCredentials.ANONYMOUS_CREDENTIALS)).isTrue(); } @Test public void isAnonymous_AwsCredentialsIdentity_false() { assertThat(CredentialUtils.isAnonymous(AwsCredentialsIdentity.create("akid", "skid"))).isFalse(); } @Test public void toCredentials_null_returnsNull() { assertThat(CredentialUtils.toCredentials(null)).isNull(); } @Test public void toCredentials_AwsSessionCredentials_doesNotCreateNewObject() { AwsSessionCredentialsIdentity input = AwsSessionCredentials.create("ak", "sk", "session"); AwsCredentials output = CredentialUtils.toCredentials(input); assertThat(output).isSameAs(input); } @Test public void toCredentials_AwsSessionCredentialsIdentity_returnsAwsSessionCredentials() { AwsCredentials awsCredentials = CredentialUtils.toCredentials(AwsSessionCredentialsIdentity.create( "akid", "skid", "session")); assertThat(awsCredentials).isInstanceOf(AwsSessionCredentials.class); AwsSessionCredentials awsSessionCredentials = (AwsSessionCredentials) awsCredentials; assertThat(awsSessionCredentials.accessKeyId()).isEqualTo("akid"); assertThat(awsSessionCredentials.secretAccessKey()).isEqualTo("skid"); assertThat(awsSessionCredentials.sessionToken()).isEqualTo("session"); } @Test public void toCredentials_AwsCredentials_returnsAsIs() { AwsCredentialsIdentity input = AwsBasicCredentials.create("ak", "sk"); AwsCredentials output = CredentialUtils.toCredentials(input); assertThat(output).isSameAs(input); } @Test public void toCredentials_AwsCredentialsIdentity_returnsAwsCredentials() { AwsCredentials awsCredentials = CredentialUtils.toCredentials(AwsCredentialsIdentity.create("akid", "skid")); assertThat(awsCredentials.accessKeyId()).isEqualTo("akid"); assertThat(awsCredentials.secretAccessKey()).isEqualTo("skid"); } @Test public void toCredentials_Anonymous_returnsAnonymous() { AwsCredentials awsCredentials = CredentialUtils.toCredentials(new AwsCredentialsIdentity() { @Override public String accessKeyId() { return null; } @Override public String secretAccessKey() { return null; } }); assertThat(awsCredentials.accessKeyId()).isNull(); assertThat(awsCredentials.secretAccessKey()).isNull(); } @Test public void toCredentialsProvider_null_returnsNull() { assertThat(CredentialUtils.toCredentialsProvider(null)).isNull(); } @Test public void toCredentialsProvider_AwsCredentialsProvider_returnsAsIs() { IdentityProvider<AwsCredentialsIdentity> input = StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid")); AwsCredentialsProvider output = CredentialUtils.toCredentialsProvider(input); assertThat(output).isSameAs(input); } @Test public void toCredentialsProvider_IdentityProvider_converts() { AwsCredentialsProvider credentialsProvider = CredentialUtils.toCredentialsProvider( StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))); AwsCredentials credentials = credentialsProvider.resolveCredentials(); assertThat(credentials.accessKeyId()).isEqualTo("akid"); assertThat(credentials.secretAccessKey()).isEqualTo("skid"); } }
1,683
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/InstanceProfileCredentialsProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.credentials; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.put; import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static java.time.temporal.ChronoUnit.HOURS; import static java.time.temporal.ChronoUnit.MINUTES; import static java.time.temporal.ChronoUnit.SECONDS; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.github.tomakehurst.wiremock.WireMockServer; import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder; import com.github.tomakehurst.wiremock.client.WireMock; import com.github.tomakehurst.wiremock.core.WireMockConfiguration; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.github.tomakehurst.wiremock.matching.RequestPattern; import com.github.tomakehurst.wiremock.matching.RequestPatternBuilder; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.time.ZoneId; import java.time.ZoneOffset; import java.util.Arrays; import java.util.List; import java.util.function.Supplier; import java.util.stream.Collectors; import org.junit.AfterClass; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.util.SdkUserAgent; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileFileSupplier; import software.amazon.awssdk.profiles.ProfileProperty; import software.amazon.awssdk.utils.DateUtils; import software.amazon.awssdk.utils.Pair; import software.amazon.awssdk.utils.StringInputStream; public class InstanceProfileCredentialsProviderTest { private static final String TOKEN_RESOURCE_PATH = "/latest/api/token"; private static final String CREDENTIALS_RESOURCE_PATH = "/latest/meta-data/iam/security-credentials/"; private static final String STUB_CREDENTIALS = "{\"AccessKeyId\":\"ACCESS_KEY_ID\",\"SecretAccessKey\":\"SECRET_ACCESS_KEY\"," + "\"Expiration\":\"" + DateUtils.formatIso8601Date(Instant.now().plus(Duration.ofDays(1))) + "\"}"; private static final String TOKEN_HEADER = "x-aws-ec2-metadata-token"; private static final String EC2_METADATA_TOKEN_TTL_HEADER = "x-aws-ec2-metadata-token-ttl-seconds"; @Rule public ExpectedException thrown = ExpectedException.none(); @Rule public WireMockRule mockMetadataEndpoint = new WireMockRule(); @Before public void methodSetup() { System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property(), "http://localhost:" + mockMetadataEndpoint.port()); } @AfterClass public static void teardown() { System.clearProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property()); } @Test public void resolveCredentials_metadataLookupDisabled_throws() { System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_DISABLED.property(), "true"); thrown.expect(SdkClientException.class); thrown.expectMessage("IMDS credentials have been disabled"); try { InstanceProfileCredentialsProvider.builder().build().resolveCredentials(); } finally { System.clearProperty(SdkSystemSetting.AWS_EC2_METADATA_DISABLED.property()); } } @Test public void resolveCredentials_requestsIncludeUserAgent() { String stubToken = "some-token"; stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withBody(stubToken))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).willReturn(aResponse().withBody("some-profile"))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).willReturn(aResponse().withBody(STUB_CREDENTIALS))); InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build(); provider.resolveCredentials(); String userAgentHeader = "User-Agent"; String userAgent = SdkUserAgent.create().userAgent(); WireMock.verify(putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)).withHeader(userAgentHeader, equalTo(userAgent))); WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).withHeader(userAgentHeader, equalTo(userAgent))); WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).withHeader(userAgentHeader, equalTo(userAgent))); } @Test public void resolveCredentials_queriesTokenResource() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withBody("some-token"))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).willReturn(aResponse().withBody("some-profile"))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).willReturn(aResponse().withBody(STUB_CREDENTIALS))); InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build(); provider.resolveCredentials(); WireMock.verify(putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)).withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600"))); } @Test public void resolveCredentials_queriesTokenResource_includedInCredentialsRequests() { String stubToken = "some-token"; stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withBody(stubToken))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).willReturn(aResponse().withBody("some-profile"))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).willReturn(aResponse().withBody(STUB_CREDENTIALS))); InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build(); provider.resolveCredentials(); WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).withHeader(TOKEN_HEADER, equalTo(stubToken))); WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).withHeader(TOKEN_HEADER, equalTo(stubToken))); } @Test public void resolveCredentials_queriesTokenResource_403Error_fallbackToInsecure() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withStatus(403).withBody("oops"))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).willReturn(aResponse().withBody("some-profile"))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).willReturn(aResponse().withBody(STUB_CREDENTIALS))); InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build(); provider.resolveCredentials(); WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH))); WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile"))); } @Test public void resolveCredentials_queriesTokenResource_404Error_fallbackToInsecure() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withStatus(404).withBody("oops"))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).willReturn(aResponse().withBody("some-profile"))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).willReturn(aResponse().withBody(STUB_CREDENTIALS))); InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build(); provider.resolveCredentials(); WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH))); WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile"))); } @Test public void resolveCredentials_queriesTokenResource_405Error_fallbackToInsecure() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withStatus(405).withBody("oops"))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).willReturn(aResponse().withBody("some-profile"))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).willReturn(aResponse().withBody(STUB_CREDENTIALS))); InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build(); provider.resolveCredentials(); WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH))); WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile"))); } @Test public void resolveCredentials_queriesTokenResource_400Error_throws() { thrown.expect(SdkClientException.class); thrown.expectMessage("Failed to load credentials from IMDS"); stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withStatus(400).withBody("oops"))); InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build(); provider.resolveCredentials(); } @Test public void resolveCredentials_queriesTokenResource_socketTimeout_fallbackToInsecure() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withBody("some-token").withFixedDelay(Integer.MAX_VALUE))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).willReturn(aResponse().withBody("some-profile"))); stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).willReturn(aResponse().withBody(STUB_CREDENTIALS))); InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build(); provider.resolveCredentials(); WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH))); WireMock.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile"))); } @Test public void resolveCredentials_endpointSettingEmpty_throws() { thrown.expect(SdkClientException.class); System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property(), ""); InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build(); provider.resolveCredentials(); } @Test public void resolveCredentials_endpointSettingHostNotExists_throws() { thrown.expect(SdkClientException.class); System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property(), "some-host-that-does-not-exist"); InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder().build(); provider.resolveCredentials(); } @Test public void resolveCredentials_customProfileFileAndName_usesCorrectEndpoint() { WireMockServer mockMetadataEndpoint_2 = new WireMockServer(WireMockConfiguration.options().dynamicPort()); mockMetadataEndpoint_2.start(); try { String stubToken = "some-token"; mockMetadataEndpoint_2.stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withBody(stubToken))); mockMetadataEndpoint_2.stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).willReturn(aResponse().withBody("some-profile"))); mockMetadataEndpoint_2.stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).willReturn(aResponse().withBody(STUB_CREDENTIALS))); String mockServer2Endpoint = "http://localhost:" + mockMetadataEndpoint_2.port(); InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider.builder() .endpoint(mockServer2Endpoint) .build(); provider.resolveCredentials(); String userAgentHeader = "User-Agent"; String userAgent = SdkUserAgent.create().userAgent(); mockMetadataEndpoint_2.verify(putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)).withHeader(userAgentHeader, equalTo(userAgent))); mockMetadataEndpoint_2.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).withHeader(userAgentHeader, equalTo(userAgent))); mockMetadataEndpoint_2.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).withHeader(userAgentHeader, equalTo(userAgent))); // all requests should have gone to the second server, and none to the other one mockMetadataEndpoint.verify(0, RequestPatternBuilder.allRequests()); } finally { mockMetadataEndpoint_2.stop(); } } @Test public void resolveCredentials_customProfileFileSupplierAndNameSettingEndpointOverride_usesCorrectEndpointFromSupplier() { System.clearProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property()); WireMockServer mockMetadataEndpoint_2 = new WireMockServer(WireMockConfiguration.options().dynamicPort()); mockMetadataEndpoint_2.start(); try { String stubToken = "some-token"; mockMetadataEndpoint_2.stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withBody(stubToken))); mockMetadataEndpoint_2.stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).willReturn(aResponse().withBody("some-profile"))); mockMetadataEndpoint_2.stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).willReturn(aResponse().withBody(STUB_CREDENTIALS))); String mockServer2Endpoint = "http://localhost:" + mockMetadataEndpoint_2.port(); ProfileFile config = configFile("profile test", Pair.of(ProfileProperty.EC2_METADATA_SERVICE_ENDPOINT, mockServer2Endpoint)); List<ProfileFile> profileFileList = Arrays.asList(credentialFile("test", "key1", "secret1"), credentialFile("test", "key2", "secret2"), credentialFile("test", "key3", "secret3")); InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider .builder() .profileFile(ProfileFileSupplier.aggregate(supply(profileFileList), () -> config)) .profileName("test") .build(); AwsCredentials awsCredentials1 = provider.resolveCredentials(); assertThat(awsCredentials1).isNotNull(); String userAgentHeader = "User-Agent"; String userAgent = SdkUserAgent.create().userAgent(); mockMetadataEndpoint_2.verify(putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)).withHeader(userAgentHeader, equalTo(userAgent))); mockMetadataEndpoint_2.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).withHeader(userAgentHeader, equalTo(userAgent))); mockMetadataEndpoint_2.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).withHeader(userAgentHeader, equalTo(userAgent))); // all requests should have gone to the second server, and none to the other one mockMetadataEndpoint.verify(0, RequestPatternBuilder.allRequests()); } finally { mockMetadataEndpoint_2.stop(); } } @Test public void resolveCredentials_customSupplierProfileFileAndNameSettingEndpointOverride_usesCorrectEndpointFromSupplier() { System.clearProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property()); WireMockServer mockMetadataEndpoint_2 = new WireMockServer(WireMockConfiguration.options().dynamicPort()); mockMetadataEndpoint_2.start(); try { String stubToken = "some-token"; mockMetadataEndpoint_2.stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withBody(stubToken))); mockMetadataEndpoint_2.stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).willReturn(aResponse().withBody("some-profile"))); mockMetadataEndpoint_2.stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).willReturn(aResponse().withBody(STUB_CREDENTIALS))); String mockServer2Endpoint = "http://localhost:" + mockMetadataEndpoint_2.port(); ProfileFile config = configFile("profile test", Pair.of(ProfileProperty.EC2_METADATA_SERVICE_ENDPOINT, mockServer2Endpoint)); Supplier<ProfileFile> supplier = () -> config; InstanceProfileCredentialsProvider provider = InstanceProfileCredentialsProvider .builder() .profileFile(supplier) .profileName("test") .build(); AwsCredentials awsCredentials1 = provider.resolveCredentials(); assertThat(awsCredentials1).isNotNull(); String userAgentHeader = "User-Agent"; String userAgent = SdkUserAgent.create().userAgent(); mockMetadataEndpoint_2.verify(putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)).withHeader(userAgentHeader, equalTo(userAgent))); mockMetadataEndpoint_2.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).withHeader(userAgentHeader, equalTo(userAgent))); mockMetadataEndpoint_2.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).withHeader(userAgentHeader, equalTo(userAgent))); // all requests should have gone to the second server, and none to the other one mockMetadataEndpoint.verify(0, RequestPatternBuilder.allRequests()); } finally { mockMetadataEndpoint_2.stop(); } } @Test public void resolveCredentials_doesNotFailIfImdsReturnsExpiredCredentials() { String credentialsResponse = "{" + "\"AccessKeyId\":\"ACCESS_KEY_ID\"," + "\"SecretAccessKey\":\"SECRET_ACCESS_KEY\"," + "\"Expiration\":\"" + DateUtils.formatIso8601Date(Instant.now().minus(Duration.ofHours(1))) + '"' + "}"; stubCredentialsResponse(aResponse().withBody(credentialsResponse)); AwsCredentials credentials = InstanceProfileCredentialsProvider.builder().build().resolveCredentials(); assertThat(credentials.accessKeyId()).isEqualTo("ACCESS_KEY_ID"); assertThat(credentials.secretAccessKey()).isEqualTo("SECRET_ACCESS_KEY"); } @Test public void resolveCredentials_onlyCallsImdsOnceEvenWithExpiredCredentials() { String credentialsResponse = "{" + "\"AccessKeyId\":\"ACCESS_KEY_ID\"," + "\"SecretAccessKey\":\"SECRET_ACCESS_KEY\"," + "\"Expiration\":\"" + DateUtils.formatIso8601Date(Instant.now().minus(Duration.ofHours(1))) + '"' + "}"; stubCredentialsResponse(aResponse().withBody(credentialsResponse)); AwsCredentialsProvider credentialsProvider = InstanceProfileCredentialsProvider.builder().build(); credentialsProvider.resolveCredentials(); int requestCountAfterOneRefresh = mockMetadataEndpoint.countRequestsMatching(RequestPattern.everything()).getCount(); credentialsProvider.resolveCredentials(); credentialsProvider.resolveCredentials(); int requestCountAfterThreeRefreshes = mockMetadataEndpoint.countRequestsMatching(RequestPattern.everything()).getCount(); assertThat(requestCountAfterThreeRefreshes).isEqualTo(requestCountAfterOneRefresh); } @Test public void resolveCredentials_failsIfImdsReturns500OnFirstCall() { String errorMessage = "XXXXX"; String credentialsResponse = "{" + "\"code\": \"InternalServiceException\"," + "\"message\": \"" + errorMessage + "\"" + "}"; stubCredentialsResponse(aResponse().withStatus(500) .withBody(credentialsResponse)); assertThatThrownBy(InstanceProfileCredentialsProvider.builder().build()::resolveCredentials) .isInstanceOf(SdkClientException.class) .hasRootCauseMessage(errorMessage); } @Test public void resolveCredentials_usesCacheIfImdsFailsOnSecondCall() { AdjustableClock clock = new AdjustableClock(); AwsCredentialsProvider credentialsProvider = credentialsProviderWithClock(clock); String successfulCredentialsResponse = "{" + "\"AccessKeyId\":\"ACCESS_KEY_ID\"," + "\"SecretAccessKey\":\"SECRET_ACCESS_KEY\"," + "\"Expiration\":\"" + DateUtils.formatIso8601Date(Instant.now()) + '"' + "}"; // Set the time to the past, so that the cache expiration time is still is in the past, and then prime the cache clock.time = Instant.now().minus(24, HOURS); stubCredentialsResponse(aResponse().withBody(successfulCredentialsResponse)); AwsCredentials credentialsBefore = credentialsProvider.resolveCredentials(); // Travel to the present time take down IMDS, so we can see if we use the cached credentials clock.time = Instant.now(); stubCredentialsResponse(aResponse().withStatus(500)); AwsCredentials credentialsAfter = credentialsProvider.resolveCredentials(); assertThat(credentialsBefore).isEqualTo(credentialsAfter); } @Test public void resolveCredentials_callsImdsIfCredentialsWithin5MinutesOfExpiration() { AdjustableClock clock = new AdjustableClock(); AwsCredentialsProvider credentialsProvider = credentialsProviderWithClock(clock); Instant now = Instant.now(); String successfulCredentialsResponse1 = "{" + "\"AccessKeyId\":\"ACCESS_KEY_ID\"," + "\"SecretAccessKey\":\"SECRET_ACCESS_KEY\"," + "\"Expiration\":\"" + DateUtils.formatIso8601Date(now) + '"' + "}"; String successfulCredentialsResponse2 = "{" + "\"AccessKeyId\":\"ACCESS_KEY_ID\"," + "\"SecretAccessKey\":\"SECRET_ACCESS_KEY2\"," + "\"Expiration\":\"" + DateUtils.formatIso8601Date(now.plus(6, HOURS)) + '"' + "}"; // Set the time to the past and call IMDS to prime the cache clock.time = now.minus(24, HOURS); stubCredentialsResponse(aResponse().withBody(successfulCredentialsResponse1)); AwsCredentials credentials24HoursAgo = credentialsProvider.resolveCredentials(); // Set the time to 10 minutes before expiration, and fail to call IMDS clock.time = now.minus(10, MINUTES); stubCredentialsResponse(aResponse().withStatus(500)); AwsCredentials credentials10MinutesAgo = credentialsProvider.resolveCredentials(); // Set the time to 10 seconds before expiration, and verify that we still call IMDS to try to get credentials in at the // last moment before expiration clock.time = now.minus(10, SECONDS); stubCredentialsResponse(aResponse().withBody(successfulCredentialsResponse2)); AwsCredentials credentials10SecondsAgo = credentialsProvider.resolveCredentials(); assertThat(credentials24HoursAgo).isEqualTo(credentials10MinutesAgo); assertThat(credentials24HoursAgo.secretAccessKey()).isEqualTo("SECRET_ACCESS_KEY"); assertThat(credentials10SecondsAgo.secretAccessKey()).isEqualTo("SECRET_ACCESS_KEY2"); } @Test public void imdsCallFrequencyIsLimited() { // Requires running the test multiple times to account for refresh jitter for (int i = 0; i < 10; i++) { AdjustableClock clock = new AdjustableClock(); AwsCredentialsProvider credentialsProvider = credentialsProviderWithClock(clock); Instant now = Instant.now(); String successfulCredentialsResponse1 = "{" + "\"AccessKeyId\":\"ACCESS_KEY_ID\"," + "\"SecretAccessKey\":\"SECRET_ACCESS_KEY\"," + "\"Expiration\":\"" + DateUtils.formatIso8601Date(now) + '"' + "}"; String successfulCredentialsResponse2 = "{" + "\"AccessKeyId\":\"ACCESS_KEY_ID2\"," + "\"SecretAccessKey\":\"SECRET_ACCESS_KEY2\"," + "\"Expiration\":\"" + DateUtils.formatIso8601Date(now.plus(6, HOURS)) + '"' + "}"; // Set the time to 5 minutes before expiration and call IMDS clock.time = now.minus(5, MINUTES); stubCredentialsResponse(aResponse().withBody(successfulCredentialsResponse1)); AwsCredentials credentials5MinutesAgo = credentialsProvider.resolveCredentials(); // Set the time to 2 seconds before expiration, and verify that do not call IMDS because it hasn't been 5 minutes yet clock.time = now.minus(2, SECONDS); stubCredentialsResponse(aResponse().withBody(successfulCredentialsResponse2)); AwsCredentials credentials2SecondsAgo = credentialsProvider.resolveCredentials(); assertThat(credentials2SecondsAgo).isEqualTo(credentials5MinutesAgo); assertThat(credentials5MinutesAgo.secretAccessKey()).isEqualTo("SECRET_ACCESS_KEY"); } } private AwsCredentialsProvider credentialsProviderWithClock(Clock clock) { InstanceProfileCredentialsProvider.BuilderImpl builder = (InstanceProfileCredentialsProvider.BuilderImpl) InstanceProfileCredentialsProvider.builder(); builder.clock(clock); return builder.build(); } private void stubCredentialsResponse(ResponseDefinitionBuilder responseDefinitionBuilder) { mockMetadataEndpoint.stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)) .willReturn(aResponse().withBody("some-token"))); mockMetadataEndpoint.stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)) .willReturn(aResponse().withBody("some-profile"))); mockMetadataEndpoint.stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")) .willReturn(responseDefinitionBuilder)); } private static class AdjustableClock extends Clock { private Instant time; @Override public ZoneId getZone() { return ZoneOffset.UTC; } @Override public Clock withZone(ZoneId zone) { throw new UnsupportedOperationException(); } @Override public Instant instant() { return time; } } private static ProfileFileSupplier supply(Iterable<ProfileFile> iterable) { return iterable.iterator()::next; } private ProfileFile credentialFile(String credentialFile) { return ProfileFile.builder() .content(new StringInputStream(credentialFile)) .type(ProfileFile.Type.CREDENTIALS) .build(); } private ProfileFile configFile(String credentialFile) { return ProfileFile.builder() .content(new StringInputStream(credentialFile)) .type(ProfileFile.Type.CONFIGURATION) .build(); } private ProfileFile credentialFile(String name, String accessKeyId, String secretAccessKey) { String contents = String.format("[%s]\naws_access_key_id = %s\naws_secret_access_key = %s\n", name, accessKeyId, secretAccessKey); return credentialFile(contents); } private ProfileFile configFile(String name, Pair<?, ?>... pairs) { String values = Arrays.stream(pairs) .map(pair -> String.format("%s=%s", pair.left(), pair.right())) .collect(Collectors.joining(System.lineSeparator())); String contents = String.format("[%s]\n%s", name, values); return configFile(contents); } }
1,684
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/ContainerCredentialsEndpointProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.credentials; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasEntry; import static software.amazon.awssdk.core.SdkSystemSetting.AWS_CONTAINER_AUTHORIZATION_TOKEN; import static software.amazon.awssdk.core.SdkSystemSetting.AWS_CONTAINER_CREDENTIALS_FULL_URI; import static software.amazon.awssdk.core.SdkSystemSetting.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI; import java.io.IOException; import java.util.Map; import org.junit.After; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.util.SdkUserAgent; import software.amazon.awssdk.testutils.EnvironmentVariableHelper; public class ContainerCredentialsEndpointProviderTest { private static final EnvironmentVariableHelper helper = new EnvironmentVariableHelper(); private static final ContainerCredentialsProvider.ContainerCredentialsEndpointProvider sut = new ContainerCredentialsProvider.ContainerCredentialsEndpointProvider(null); @Before public void clearContainerVariablesIncaseWereRunningTestsOnEC2() { helper.remove(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI); } @After public void restoreOriginal() { helper.reset(); } @Test public void takesUriFromOverride() throws IOException { String hostname = "http://localhost:8080"; String path = "/endpoint"; helper.set(AWS_CONTAINER_CREDENTIALS_RELATIVE_URI, path); assertThat(new ContainerCredentialsProvider.ContainerCredentialsEndpointProvider(hostname).endpoint().toString(), equalTo(hostname + path)); } @Test public void takesUriFromTheEnvironmentVariable() throws IOException { String fullUri = "http://localhost:8080/endpoint"; helper.set(AWS_CONTAINER_CREDENTIALS_FULL_URI.environmentVariable(), fullUri); assertThat(sut.endpoint().toString(), equalTo(fullUri)); } @Test public void theLoopbackAddressIsAlsoAcceptable() throws IOException { String fullUri = "http://127.0.0.1:9851/endpoint"; helper.set(AWS_CONTAINER_CREDENTIALS_FULL_URI.environmentVariable(), fullUri); assertThat(sut.endpoint().toString(), equalTo(fullUri)); } @Test public void theLoopbackIpv6AddressIsAlsoAcceptable() throws IOException { String fullUri = "http://[::1]:9851/endpoint"; helper.set(AWS_CONTAINER_CREDENTIALS_FULL_URI.environmentVariable(), fullUri); assertThat(sut.endpoint().toString(), equalTo(fullUri)); } @Test public void anyHttpsAddressIsAlsoAcceptable() throws IOException { String fullUri = "https://192.168.10.120:9851/endpoint"; helper.set(AWS_CONTAINER_CREDENTIALS_FULL_URI.environmentVariable(), fullUri); assertThat(sut.endpoint().toString(), equalTo(fullUri)); } @Test public void anyHttpsIpv6AddressIsAlsoAcceptable() throws IOException { String fullUri = "https://[::FFFF:152.16.24.123]/endpoint"; helper.set(AWS_CONTAINER_CREDENTIALS_FULL_URI.environmentVariable(), fullUri); assertThat(sut.endpoint().toString(), equalTo(fullUri)); } @Test(expected = SdkClientException.class) public void nonLoopbackAddressIsNotAcceptable() throws IOException { String fullUri = "http://192.168.10.120:9851/endpoint"; helper.set(AWS_CONTAINER_CREDENTIALS_FULL_URI.environmentVariable(), fullUri); assertThat(sut.endpoint().toString(), equalTo(fullUri)); } @Test(expected = SdkClientException.class) public void nonLoopbackIpv6AddressIsNotAcceptable() throws IOException { String fullUri = "http://[::FFFF:152.16.24.123]/endpoint"; helper.set(AWS_CONTAINER_CREDENTIALS_FULL_URI.environmentVariable(), fullUri); assertThat(sut.endpoint().toString(), equalTo(fullUri)); } @Test(expected = SdkClientException.class) public void onlyLocalHostAddressesAreValid() throws IOException { helper.set(AWS_CONTAINER_CREDENTIALS_FULL_URI.environmentVariable(), "http://google.com/endpoint"); sut.endpoint(); } @Test public void authorizationHeaderIsPresentIfEnvironmentVariableSet() { helper.set(AWS_CONTAINER_AUTHORIZATION_TOKEN.environmentVariable(), "hello authorized world!"); Map<String, String> headers = sut.headers(); assertThat(headers.size(), equalTo(2)); assertThat(headers, hasEntry("Authorization", "hello authorized world!")); assertThat(headers, hasEntry("User-Agent", SdkUserAgent.create().userAgent())); } }
1,685
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/AwsCredentialsProviderChainTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.credentials; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.Arrays; import org.junit.Test; import org.junit.jupiter.api.function.Executable; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.utils.StringInputStream; public class AwsCredentialsProviderChainTest { /** * Tests that, by default, the chain remembers which provider was able to * provide credentials, and only calls that provider for any additional * calls to getCredentials. */ @Test public void resolveCredentials_reuseEnabled_reusesLastProvider() throws Exception { MockCredentialsProvider provider1 = new MockCredentialsProvider("Failed!"); MockCredentialsProvider provider2 = new MockCredentialsProvider(); AwsCredentialsProviderChain chain = AwsCredentialsProviderChain.builder() .credentialsProviders(provider1, provider2) .build(); assertEquals(0, provider1.getCredentialsCallCount); assertEquals(0, provider2.getCredentialsCallCount); chain.resolveCredentials(); assertEquals(1, provider1.getCredentialsCallCount); assertEquals(1, provider2.getCredentialsCallCount); chain.resolveCredentials(); assertEquals(1, provider1.getCredentialsCallCount); assertEquals(2, provider2.getCredentialsCallCount); chain.resolveCredentials(); assertEquals(1, provider1.getCredentialsCallCount); assertEquals(3, provider2.getCredentialsCallCount); } /** * Tests that, when provider caching is disabled, the chain will always try * all providers in the chain, starting with the first, until it finds a * provider that can return credentials. */ @Test public void resolveCredentials_reuseDisabled_alwaysGoesThroughChain() throws Exception { MockCredentialsProvider provider1 = new MockCredentialsProvider("Failed!"); MockCredentialsProvider provider2 = new MockCredentialsProvider(); AwsCredentialsProviderChain chain = AwsCredentialsProviderChain.builder() .credentialsProviders(provider1, provider2) .reuseLastProviderEnabled(false) .build(); assertEquals(0, provider1.getCredentialsCallCount); assertEquals(0, provider2.getCredentialsCallCount); chain.resolveCredentials(); assertEquals(1, provider1.getCredentialsCallCount); assertEquals(1, provider2.getCredentialsCallCount); chain.resolveCredentials(); assertEquals(2, provider1.getCredentialsCallCount); assertEquals(2, provider2.getCredentialsCallCount); } @Test public void resolveCredentials_missingProfile_usesNextProvider() { ProfileCredentialsProvider provider = new ProfileCredentialsProvider.BuilderImpl() .defaultProfileFileLoader(() -> ProfileFile.builder() .content(new StringInputStream("")) .type(ProfileFile.Type.CONFIGURATION) .build()) .build(); MockCredentialsProvider provider2 = new MockCredentialsProvider(); AwsCredentialsProviderChain chain = AwsCredentialsProviderChain.builder().credentialsProviders(provider, provider2).build(); chain.resolveCredentials(); assertEquals(1, provider2.getCredentialsCallCount); } /** * Tests that resolveCredentials throws an thrown if all providers in the * chain fail to provide credentials. */ @Test public void resolveCredentials_allProvidersFail_throwsExceptionWithMessageFromAllProviders() { MockCredentialsProvider provider1 = new MockCredentialsProvider("Failed!"); MockCredentialsProvider provider2 = new MockCredentialsProvider("Bad!"); AwsCredentialsProviderChain chain = AwsCredentialsProviderChain.builder() .credentialsProviders(provider1, provider2) .build(); SdkClientException e = assertThrows(SdkClientException.class, () -> chain.resolveCredentials()); assertThat(e.getMessage()).contains(provider1.exceptionMessage); assertThat(e.getMessage()).contains(provider2.exceptionMessage); } @Test public void resolveCredentials_emptyChain_throwsException() { assertThrowsIllegalArgument(() -> AwsCredentialsProviderChain.of()); assertThrowsIllegalArgument(() -> AwsCredentialsProviderChain .builder() .credentialsProviders() .build()); assertThrowsIllegalArgument(() -> AwsCredentialsProviderChain .builder() .credentialsProviders(Arrays.asList()) .build()); } private void assertThrowsIllegalArgument(Executable executable) { IllegalArgumentException e = assertThrows(IllegalArgumentException.class, executable); assertThat(e.getMessage()).contains("No credential providers were specified."); } /** * Tests that the chain is setup correctly with the overloaded methods that accept the AwsCredentialsProvider type. */ @Test public void createMethods_withOldCredentialsType_work() { AwsCredentialsProvider provider = StaticCredentialsProvider.create(AwsBasicCredentials.create( "accessKey", "secretKey")); assertChainResolvesCorrectly(AwsCredentialsProviderChain.of(provider)); assertChainResolvesCorrectly(AwsCredentialsProviderChain.builder().credentialsProviders(provider).build()); assertChainResolvesCorrectly(AwsCredentialsProviderChain.builder().credentialsProviders(Arrays.asList(provider)).build()); assertChainResolvesCorrectly(AwsCredentialsProviderChain.builder().addCredentialsProvider(provider).build()); } /** * Tests that the chain is setup correctly with the overloaded methods that accept the IdentityProvider type. */ @Test public void createMethods_withNewCredentialsType_work() { IdentityProvider<AwsCredentialsIdentity> provider = StaticCredentialsProvider.create(AwsBasicCredentials.create( "accessKey", "secretKey")); assertChainResolvesCorrectly(AwsCredentialsProviderChain.of(provider)); assertChainResolvesCorrectly(AwsCredentialsProviderChain.builder().credentialsProviders(provider).build()); assertChainResolvesCorrectly(AwsCredentialsProviderChain.builder().credentialsIdentityProviders(Arrays.asList(provider)).build()); assertChainResolvesCorrectly(AwsCredentialsProviderChain.builder().addCredentialsProvider(provider).build()); } private static void assertChainResolvesCorrectly(AwsCredentialsProviderChain chain) { AwsCredentials credentials = chain.resolveCredentials(); assertThat(credentials.accessKeyId()).isEqualTo("accessKey"); assertThat(credentials.secretAccessKey()).isEqualTo("secretKey"); } private static final class MockCredentialsProvider implements AwsCredentialsProvider { private final StaticCredentialsProvider staticCredentialsProvider; private final String exceptionMessage; int getCredentialsCallCount = 0; private MockCredentialsProvider() { this(null); } private MockCredentialsProvider(String exceptionMessage) { staticCredentialsProvider = StaticCredentialsProvider.create(AwsBasicCredentials.create("accessKey", "secretKey")); this.exceptionMessage = exceptionMessage; } @Override public AwsCredentials resolveCredentials() { getCredentialsCallCount++; if (exceptionMessage != null) { throw new RuntimeException(exceptionMessage); } else { return staticCredentialsProvider.resolveCredentials(); } } } }
1,686
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/ProcessCredentialsProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.credentials; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertNotNull; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UncheckedIOException; import java.time.Duration; import java.time.Instant; import org.assertj.core.api.Assertions; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.utils.DateUtils; import software.amazon.awssdk.utils.IoUtils; import software.amazon.awssdk.utils.Platform; public class ProcessCredentialsProviderTest { private static final String PROCESS_RESOURCE_PATH = "/resources/process/"; private static final String RANDOM_SESSION_TOKEN = "RANDOM_TOKEN"; private static String scriptLocation; private static String errorScriptLocation; @BeforeClass public static void setup() { scriptLocation = copyHappyCaseProcessCredentialsScript(); errorScriptLocation = copyErrorCaseProcessCredentialsScript(); } @AfterClass public static void teardown() { if (scriptLocation != null && !new File(scriptLocation).delete()) { throw new IllegalStateException("Failed to delete file: " + scriptLocation); } if (errorScriptLocation != null && !new File(errorScriptLocation).delete()) { throw new IllegalStateException("Failed to delete file: " + errorScriptLocation); } } @Test public void staticCredentialsCanBeLoaded() { AwsCredentials credentials = ProcessCredentialsProvider.builder() .command(scriptLocation + " accessKeyId secretAccessKey") .build() .resolveCredentials(); Assert.assertFalse(credentials instanceof AwsSessionCredentials); Assert.assertEquals("accessKeyId", credentials.accessKeyId()); Assert.assertEquals("secretAccessKey", credentials.secretAccessKey()); } @Test public void sessionCredentialsCanBeLoaded() { ProcessCredentialsProvider credentialsProvider = ProcessCredentialsProvider.builder() .command(scriptLocation + " accessKeyId secretAccessKey sessionToken " + DateUtils.formatIso8601Date(Instant.now())) .credentialRefreshThreshold(Duration.ofSeconds(1)) .build(); AwsCredentials credentials = credentialsProvider.resolveCredentials(); Assert.assertTrue(credentials instanceof AwsSessionCredentials); AwsSessionCredentials sessionCredentials = (AwsSessionCredentials) credentials; Assert.assertEquals("accessKeyId", sessionCredentials.accessKeyId()); Assert.assertEquals("secretAccessKey", sessionCredentials.secretAccessKey()); assertNotNull(sessionCredentials.sessionToken()); } @Test public void resultsAreCached() { ProcessCredentialsProvider credentialsProvider = ProcessCredentialsProvider.builder() .command(scriptLocation + " accessKeyId secretAccessKey sessionToken " + DateUtils.formatIso8601Date(Instant.now().plusSeconds(20))) .build(); AwsCredentials request1 = credentialsProvider.resolveCredentials(); AwsCredentials request2 = credentialsProvider.resolveCredentials(); Assert.assertEquals(request1, request2); } @Test public void expirationBufferOverrideIsApplied() { ProcessCredentialsProvider credentialsProvider = ProcessCredentialsProvider.builder() .command(String.format("%s accessKeyId secretAccessKey %s %s", scriptLocation, RANDOM_SESSION_TOKEN, DateUtils.formatIso8601Date(Instant.now().plusSeconds(20)))) .credentialRefreshThreshold(Duration.ofSeconds(20)) .build(); AwsCredentials request1 = credentialsProvider.resolveCredentials(); AwsCredentials request2 = credentialsProvider.resolveCredentials(); Assert.assertNotEquals(request1, request2); } @Test public void processFailed_shouldContainErrorMessage() { ProcessCredentialsProvider credentialsProvider = ProcessCredentialsProvider.builder() .command(errorScriptLocation) .credentialRefreshThreshold(Duration.ofSeconds(20)) .build(); assertThatThrownBy(credentialsProvider::resolveCredentials) .satisfies(throwable -> assertThat(throwable.getCause()) .hasMessageContaining("(125) with error message: Some error case")); } @Test public void lackOfExpirationIsCachedForever() { ProcessCredentialsProvider credentialsProvider = ProcessCredentialsProvider.builder() .command(scriptLocation + " accessKeyId secretAccessKey sessionToken") .credentialRefreshThreshold(Duration.ofSeconds(20)) .build(); AwsCredentials request1 = credentialsProvider.resolveCredentials(); AwsCredentials request2 = credentialsProvider.resolveCredentials(); Assert.assertEquals(request1, request2); } @Test(expected = IllegalStateException.class) public void processOutputLimitIsEnforced() { ProcessCredentialsProvider.builder() .command(scriptLocation + " accessKeyId secretAccessKey") .processOutputLimit(1) .build() .resolveCredentials(); } @Test public void processOutputLimitDefaultPassesLargeInput() { String LONG_SESSION_TOKEN = "lYzvmByqdS1E69QQVEavDDHabQ2GuYKYABKRA4xLbAXpdnFtV030UH4" + "bQoZWCDcfADFvBwBm3ixEFTYMjn5XQozpFV2QAsWHirCVcEJ5DC60KPCNBcDi4KLNJfbsp3r6kKTOmYOeqhEyiC4emDX33X2ppZsa5" + "1iwr6ShIZPOUPmuR4WDglmWubgO2q5tZv48xA5idkcHEmtGdoL343sY24q4gMh21eeBnF6ikjZdfvZ0Mn86UQ8r05AD346rSwM5bFs" + "t019ZkJIjLHD3HoKJ44EndRvSvQClXfJCmmQDH5INiXdFLLNm0dzT3ynbVIW5x1YYBWptyts4NUSy2eJ3dTPjYICpQVCkbuNVA7PqR" + "ctUyE8lU7uvnrIVnx9xTgl34J6D9VJKHQkPuGvbtN6w4CVtXoPAQcE8tlkKyOQmIeqEahhaqLW15t692SI6hwBW0b8DxCQawX5ukt4" + "f5gZoRFz3u8qHMSnm5oEnTgv7C5AAs0V680YvelFMNYvSoSbDnoThxfTIG9msj7WBh7iNa7mI8TXmvOegQtDWR011ZOo8dR3jnhWNH" + "nSW4CRB7iSC5DMZ2y56dYS28XGBl01LYXF5ZTJJfLwQEhbRWSTdXIBJq07E0YxRu0SaLokA4uknOoicwXnD7LMCld4hFjuypYgWBuk" + "3pC09CPA0MJjQNTTAvxGqDTqSWoXWDZRIMUWyGyz3FCkpPUjv4mIpVYt2bGl6cHsMBzVnpL6yXMCw2mNqJx8Rvi4gQaHH6LzvHbVKR" + "w4kE53703DNOc8cA9Zc0efJa4NHOFxc4XmMOtjGW7vbWPp0CTVCJLG94ddSFJrimpamPM59bs12x2ih51EpOFR5ITIxJnd79HEkYDU" + "xRIOuPIe4VpM01RnFN4g3ChDqmjQ03wQY9I8Mvh59u3MujggQfwAhCc84MAz0jVukoMfhAAhMNUPLuwRj0qpqr6B3DdKZ4KDFWF2Ga" + "Iu1sEFlKvPdfF1uefbTj6YdjUciWu1UBH47VbIcTbvbwmUiu2javB21kOenyDoelK5GUM4u0uPeXIOOhtZsJb8kz88h1joWkaKr2fc" + "jrIS08FM47Y4Z2Mi4zfwyN54L"; ProcessCredentialsProvider credentialsProvider = ProcessCredentialsProvider.builder() .command(scriptLocation + " accessKeyId secretAccessKey " + LONG_SESSION_TOKEN) .build(); AwsSessionCredentials sessionCredentials = (AwsSessionCredentials) credentialsProvider.resolveCredentials(); Assertions.assertThat(sessionCredentials.accessKeyId()).isEqualTo("accessKeyId"); Assertions.assertThat(sessionCredentials.sessionToken()).isNotNull(); } @Test public void closeDoesNotRaise() { ProcessCredentialsProvider credentialsProvider = ProcessCredentialsProvider.builder() .command(scriptLocation + " accessKeyId secretAccessKey sessionToken") .build(); credentialsProvider.resolveCredentials(); credentialsProvider.close(); } public static String copyHappyCaseProcessCredentialsScript() { String scriptClasspathFilename = Platform.isWindows() ? "windows-credentials-script.bat" : "linux-credentials-script.sh"; return copyProcessCredentialsScript(scriptClasspathFilename); } public static String copyErrorCaseProcessCredentialsScript() { String scriptClasspathFilename = Platform.isWindows() ? "windows-credentials-error-script.bat" : "linux-credentials-error-script.sh"; return copyProcessCredentialsScript(scriptClasspathFilename); } public static String copyProcessCredentialsScript(String scriptClasspathFilename) { String scriptClasspathLocation = PROCESS_RESOURCE_PATH + scriptClasspathFilename; InputStream scriptInputStream = null; OutputStream scriptOutputStream = null; try { scriptInputStream = ProcessCredentialsProviderTest.class.getResourceAsStream(scriptClasspathLocation); File scriptFileOnDisk = File.createTempFile("ProcessCredentialsProviderTest", scriptClasspathFilename); scriptFileOnDisk.deleteOnExit(); if (!scriptFileOnDisk.setExecutable(true)) { throw new IllegalStateException("Could not make " + scriptFileOnDisk + " executable."); } scriptOutputStream = new FileOutputStream(scriptFileOnDisk); IoUtils.copy(scriptInputStream, scriptOutputStream); return scriptFileOnDisk.getAbsolutePath(); } catch (IOException e) { throw new UncheckedIOException(e); } finally { IoUtils.closeQuietly(scriptInputStream, null); IoUtils.closeQuietly(scriptOutputStream, null); } } }
1,687
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/StaticCredentialsProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.credentials; import static org.junit.Assert.assertEquals; import org.junit.Test; public class StaticCredentialsProviderTest { @Test public void getAwsCredentials_ReturnsSameCredentials() throws Exception { final AwsCredentials credentials = new AwsBasicCredentials("akid", "skid"); final AwsCredentials actualCredentials = StaticCredentialsProvider.create(credentials).resolveCredentials(); assertEquals(credentials, actualCredentials); } @Test public void getSessionAwsCredentials_ReturnsSameCredentials() throws Exception { final AwsSessionCredentials credentials = AwsSessionCredentials.create("akid", "skid", "token"); final AwsCredentials actualCredentials = StaticCredentialsProvider.create(credentials).resolveCredentials(); assertEquals(credentials, actualCredentials); } @Test(expected = RuntimeException.class) public void nullCredentials_ThrowsIllegalArgumentException() { StaticCredentialsProvider.create(null); } }
1,688
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/internal/EndpointModeTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.credentials.internal; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static software.amazon.awssdk.auth.credentials.internal.Ec2MetadataConfigProvider.EndpointMode.IPV4; import static software.amazon.awssdk.auth.credentials.internal.Ec2MetadataConfigProvider.EndpointMode.IPV6; import org.junit.jupiter.api.Test; public class EndpointModeTest { @Test public void fromString_caseInsensitive() { assertThat(Ec2MetadataConfigProvider.EndpointMode.fromValue("iPv6")).isEqualTo(IPV6); assertThat(Ec2MetadataConfigProvider.EndpointMode.fromValue("iPv4")).isEqualTo(IPV4); } @Test public void fromString_unknownValue_throws() { assertThatThrownBy(() -> Ec2MetadataConfigProvider.EndpointMode.fromValue("unknown")) .isInstanceOf(IllegalArgumentException.class); } @Test public void fromString_nullValue_returnsNull() { assertThat(Ec2MetadataConfigProvider.EndpointMode.fromValue(null)).isNull(); } }
1,689
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/internal/AwsSessionCredentialsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.credentials.internal; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.credentials.AwsSessionCredentials; public class AwsSessionCredentialsTest { private static final String ACCESS_KEY_ID = "accessKeyId"; private static final String SECRET_ACCESS_KEY = "secretAccessKey"; private static final String SESSION_TOKEN = "sessionToken"; public void equalsHashcode() { EqualsVerifier.forClass(AwsSessionCredentials.class) .verify(); } @Test public void emptyBuilder_ThrowsException() { assertThrows(NullPointerException.class, () -> AwsSessionCredentials.builder().build()); } @Test public void builderMissingSessionToken_ThrowsException() { assertThrows(NullPointerException.class, () -> AwsSessionCredentials.builder() .accessKeyId(ACCESS_KEY_ID) .secretAccessKey(SECRET_ACCESS_KEY) .build()); } @Test public void builderMissingAccessKeyId_ThrowsException() { assertThrows(NullPointerException.class, () -> AwsSessionCredentials.builder() .secretAccessKey(SECRET_ACCESS_KEY) .sessionToken(SESSION_TOKEN) .build()); } @Test public void create_isSuccessful() { AwsSessionCredentials identity = AwsSessionCredentials.create(ACCESS_KEY_ID, SECRET_ACCESS_KEY, SESSION_TOKEN); assertEquals(ACCESS_KEY_ID, identity.accessKeyId()); assertEquals(SECRET_ACCESS_KEY, identity.secretAccessKey()); assertEquals(SESSION_TOKEN, identity.sessionToken()); } @Test public void build_isSuccessful() { AwsSessionCredentials identity = AwsSessionCredentials.builder() .accessKeyId(ACCESS_KEY_ID) .secretAccessKey(SECRET_ACCESS_KEY) .sessionToken(SESSION_TOKEN) .build(); assertEquals(ACCESS_KEY_ID, identity.accessKeyId()); assertEquals(SECRET_ACCESS_KEY, identity.secretAccessKey()); assertEquals(SESSION_TOKEN, identity.sessionToken()); } }
1,690
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/internal/Ec2MetadataConfigProviderEndpointModeTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.credentials.internal; import static org.assertj.core.api.Assertions.assertThat; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.function.Supplier; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileFileSystemSetting; import software.amazon.awssdk.testutils.EnvironmentVariableHelper; @RunWith(Parameterized.class) public class Ec2MetadataConfigProviderEndpointModeTest { private static final String TEST_PROFILES_PATH_PREFIX = "/software/amazon/awssdk/auth/credentials/internal/ec2metadataconfigprovider/"; private static final EnvironmentVariableHelper ENVIRONMENT_VARIABLE_HELPER = new EnvironmentVariableHelper(); private static final String CUSTOM_PROFILE = "myprofile"; @Parameterized.Parameter public TestCase testCase; @Rule public ExpectedException thrown = ExpectedException.none(); @Parameterized.Parameters(name = "{0}") public static Iterable<Object> testCases() { return Arrays.asList( new TestCase().expectedEndpointMode(null).expectedEndpointMode(Ec2MetadataConfigProvider.EndpointMode.IPV4), new TestCase().envEndpointMode("ipv4").expectedEndpointMode(Ec2MetadataConfigProvider.EndpointMode.IPV4), new TestCase().envEndpointMode("IPv4").expectedEndpointMode(Ec2MetadataConfigProvider.EndpointMode.IPV4), new TestCase().envEndpointMode("ipv6").expectedEndpointMode(Ec2MetadataConfigProvider.EndpointMode.IPV6), new TestCase().envEndpointMode("IPv6").expectedEndpointMode(Ec2MetadataConfigProvider.EndpointMode.IPV6), new TestCase().envEndpointMode("Ipv99").expectedException(IllegalArgumentException.class), new TestCase().systemPropertyEndpointMode("ipv4").expectedEndpointMode(Ec2MetadataConfigProvider.EndpointMode.IPV4), new TestCase().systemPropertyEndpointMode("IPv4").expectedEndpointMode(Ec2MetadataConfigProvider.EndpointMode.IPV4), new TestCase().systemPropertyEndpointMode("ipv6").expectedEndpointMode(Ec2MetadataConfigProvider.EndpointMode.IPV6), new TestCase().systemPropertyEndpointMode("IPv6").expectedEndpointMode(Ec2MetadataConfigProvider.EndpointMode.IPV6), new TestCase().systemPropertyEndpointMode("Ipv99").expectedException(IllegalArgumentException.class), new TestCase().sharedConfigFile(TEST_PROFILES_PATH_PREFIX + "endpoint_mode_ipv6") .expectedEndpointMode(Ec2MetadataConfigProvider.EndpointMode.IPV6), new TestCase().sharedConfigFile(TEST_PROFILES_PATH_PREFIX + "endpoint_mode_invalidValue") .expectedException(IllegalArgumentException.class), // System property takes highest precedence new TestCase().systemPropertyEndpointMode("ipv6").envEndpointMode("ipv4") .expectedEndpointMode(Ec2MetadataConfigProvider.EndpointMode.IPV6), new TestCase().systemPropertyEndpointMode("ipv6").sharedConfigFile(TEST_PROFILES_PATH_PREFIX + "endpoint_mode_ipv4") .expectedEndpointMode(Ec2MetadataConfigProvider.EndpointMode.IPV6), // env var has higher precedence than shared config new TestCase().envEndpointMode("ipv6").sharedConfigFile(TEST_PROFILES_PATH_PREFIX + "endpoint_mode_ipv4") .expectedEndpointMode(Ec2MetadataConfigProvider.EndpointMode.IPV6), // Test custom profile supplier and custom profile name new TestCase().sharedConfigFile(TEST_PROFILES_PATH_PREFIX + "endpoint_mode_ipv6_custom_profile") .customProfileName(CUSTOM_PROFILE).expectedEndpointMode(Ec2MetadataConfigProvider.EndpointMode.IPV6), new TestCase().customProfileFile(Ec2MetadataConfigProviderEndpointModeTest::customProfileFile) .customProfileName(CUSTOM_PROFILE).expectedEndpointMode(Ec2MetadataConfigProvider.EndpointMode.IPV6) ); } @Before public void setup() { ENVIRONMENT_VARIABLE_HELPER.reset(); System.clearProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE.property()); if (testCase.envEndpointMode != null) { ENVIRONMENT_VARIABLE_HELPER.set(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE.environmentVariable(), testCase.envEndpointMode); } if (testCase.systemPropertyEndpointMode != null) { System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE.property(), testCase.systemPropertyEndpointMode); } if (testCase.sharedConfigFile != null) { ENVIRONMENT_VARIABLE_HELPER.set(ProfileFileSystemSetting.AWS_CONFIG_FILE.environmentVariable(), getTestFilePath(testCase.sharedConfigFile)); } if (testCase.expectedException != null) { thrown.expect(testCase.expectedException); } } @After public void teardown() { ENVIRONMENT_VARIABLE_HELPER.reset(); System.clearProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE.property()); } @Test public void resolvesCorrectEndpointMode() { Ec2MetadataConfigProvider configProvider = Ec2MetadataConfigProvider.builder() .profileFile(testCase.customProfileFile) .profileName(testCase.customProfileName) .build(); assertThat(configProvider.getEndpointMode()).isEqualTo(testCase.expectedEndpointMode); } private static String getTestFilePath(String testFile) { return Ec2MetadataConfigProviderEndpointModeTest.class.getResource(testFile).getFile(); } private static ProfileFile customProfileFile() { String content = "[profile myprofile]\n" + "ec2_metadata_service_endpoint_mode=ipv6\n"; return ProfileFile.builder() .type(ProfileFile.Type.CONFIGURATION) .content(new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8))) .build(); } private static class TestCase { private String envEndpointMode; private String systemPropertyEndpointMode; private String sharedConfigFile; private Supplier<ProfileFile> customProfileFile; private String customProfileName; private Ec2MetadataConfigProvider.EndpointMode expectedEndpointMode; private Class<? extends Throwable> expectedException; public TestCase envEndpointMode(String envEndpointMode) { this.envEndpointMode = envEndpointMode; return this; } public TestCase systemPropertyEndpointMode(String systemPropertyEndpointMode) { this.systemPropertyEndpointMode = systemPropertyEndpointMode; return this; } public TestCase sharedConfigFile(String sharedConfigFile) { this.sharedConfigFile = sharedConfigFile; return this; } public TestCase customProfileFile(Supplier<ProfileFile> customProfileFile) { this.customProfileFile = customProfileFile; return this; } private TestCase customProfileName(String customProfileName) { this.customProfileName = customProfileName; return this; } public TestCase expectedEndpointMode(Ec2MetadataConfigProvider.EndpointMode expectedEndpointMode) { this.expectedEndpointMode = expectedEndpointMode; return this; } public TestCase expectedException(Class<? extends Throwable> expectedException) { this.expectedException = expectedException; return this; } @Override public String toString() { return "TestCase{" + "envEndpointMode='" + envEndpointMode + '\'' + ", systemPropertyEndpointMode='" + systemPropertyEndpointMode + '\'' + ", sharedConfigFile='" + sharedConfigFile + '\'' + ", customProfileFile=" + customProfileFile + ", customProfileName='" + customProfileName + '\'' + ", expectedEndpointMode=" + expectedEndpointMode + ", expectedException=" + expectedException + '}'; } } }
1,691
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/internal/Ec2MetadataConfigProviderEndpointOverrideTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.credentials.internal; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.profiles.ProfileFileSystemSetting; import software.amazon.awssdk.testutils.EnvironmentVariableHelper; @RunWith(Parameterized.class) public class Ec2MetadataConfigProviderEndpointOverrideTest { private static final String TEST_PROFILES_PATH_PREFIX = "/software/amazon/awssdk/auth/credentials/internal/ec2metadataconfigprovider/"; private static final EnvironmentVariableHelper ENVIRONMENT_VARIABLE_HELPER = new EnvironmentVariableHelper(); @Parameterized.Parameter public TestCase testCase; @Rule public ExpectedException thrown = ExpectedException.none(); @Parameterized.Parameters(name = "{0}") public static Iterable<Object> testCases() { return Arrays.<Object>asList( new TestCase().expectedEndpointOverride(null), new TestCase().envEndpointOverride("my-custom-imds").expectedEndpointOverride("my-custom-imds"), new TestCase().systemPropertyEndpointOverride("my-custom-imds").expectedEndpointOverride("my-custom-imds"), new TestCase().sharedConfigFile(TEST_PROFILES_PATH_PREFIX + "endpoint_override") .expectedEndpointOverride("my-custom-imds-profile"), // System property takes highest precedence new TestCase().systemPropertyEndpointOverride("my-systemprop-endpoint").envEndpointOverride("my-env-endpoint") .expectedEndpointOverride("my-systemprop-endpoint"), new TestCase().systemPropertyEndpointOverride("my-systemprop-endpoint").sharedConfigFile(TEST_PROFILES_PATH_PREFIX + "endpoint_override") .expectedEndpointOverride("my-systemprop-endpoint"), // // env var has higher precedence than shared config new TestCase().envEndpointOverride("my-env-endpoint").sharedConfigFile(TEST_PROFILES_PATH_PREFIX + "endpoint_override") .expectedEndpointOverride("my-env-endpoint") ); } @Before public void setup() { ENVIRONMENT_VARIABLE_HELPER.reset(); System.clearProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property()); if (testCase.envEndpointOverride != null) { ENVIRONMENT_VARIABLE_HELPER.set(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.environmentVariable(), testCase.envEndpointOverride); } if (testCase.systemPropertyEndpointOverride != null) { System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property(), testCase.systemPropertyEndpointOverride); } if (testCase.sharedConfigFile != null) { ENVIRONMENT_VARIABLE_HELPER.set(ProfileFileSystemSetting.AWS_CONFIG_FILE.environmentVariable(), getTestFilePath(testCase.sharedConfigFile)); } if (testCase.expectedException != null) { thrown.expect(testCase.expectedException); } } @After public void teardown() { ENVIRONMENT_VARIABLE_HELPER.reset(); System.clearProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property()); } @Test public void resolvesCorrectEndpointOverride() { String endpointOverride = Ec2MetadataConfigProvider.builder().build().getEndpointOverride(); assertThat(endpointOverride).isEqualTo(testCase.expectedEndpointOverride); } private static String getTestFilePath(String testFile) { return Ec2MetadataConfigProviderEndpointOverrideTest.class.getResource(testFile).getFile(); } private static class TestCase { private String envEndpointOverride; private String systemPropertyEndpointOverride; private String sharedConfigFile; private String expectedEndpointOverride; private Class<? extends Throwable> expectedException; public TestCase envEndpointOverride(String envEndpointOverride) { this.envEndpointOverride = envEndpointOverride; return this; } public TestCase systemPropertyEndpointOverride(String systemPropertyEndpointOverride) { this.systemPropertyEndpointOverride = systemPropertyEndpointOverride; return this; } public TestCase sharedConfigFile(String sharedConfigFile) { this.sharedConfigFile = sharedConfigFile; return this; } public TestCase expectedEndpointOverride(String expectedEndpointOverride) { this.expectedEndpointOverride = expectedEndpointOverride; return this; } public TestCase expectedException(Class<? extends Throwable> expectedException) { this.expectedException = expectedException; return this; } @Override public String toString() { return "TestCase{" + "envEndpointOverride='" + envEndpointOverride + '\'' + ", systemPropertyEndpointOverride='" + systemPropertyEndpointOverride + '\'' + ", sharedConfigFile='" + sharedConfigFile + '\'' + ", expectedEndpointOverride='" + expectedEndpointOverride + '\'' + ", expectedException=" + expectedException + '}'; } } }
1,692
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/internal/LazyAwsCredentialsProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.credentials.internal; import java.util.function.Supplier; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.utils.SdkAutoCloseable; public class LazyAwsCredentialsProviderTest { @SuppressWarnings("unchecked") private Supplier<AwsCredentialsProvider> credentialsConstructor = Mockito.mock(Supplier.class); private AwsCredentialsProvider credentials = Mockito.mock(AwsCredentialsProvider.class); @BeforeEach public void reset() { Mockito.reset(credentials, credentialsConstructor); Mockito.when(credentialsConstructor.get()).thenReturn(credentials); } @Test public void creationDoesntInvokeSupplier() { LazyAwsCredentialsProvider.create(credentialsConstructor); Mockito.verifyNoMoreInteractions(credentialsConstructor); } @Test public void resolveCredentialsInvokesSupplierExactlyOnce() { LazyAwsCredentialsProvider credentialsProvider = LazyAwsCredentialsProvider.create(credentialsConstructor); credentialsProvider.resolveCredentials(); credentialsProvider.resolveCredentials(); Mockito.verify(credentialsConstructor, Mockito.times(1)).get(); Mockito.verify(credentials, Mockito.times(2)).resolveCredentials(); } @Test public void delegatesClosesInitializerAndValue() { CloseableSupplier initializer = Mockito.mock(CloseableSupplier.class); CloseableCredentialsProvider value = Mockito.mock(CloseableCredentialsProvider.class); Mockito.when(initializer.get()).thenReturn(value); LazyAwsCredentialsProvider.create(initializer).close(); Mockito.verify(initializer).close(); Mockito.verify(value).close(); } @Test public void delegatesClosesInitializerEvenIfGetFails() { CloseableSupplier initializer = Mockito.mock(CloseableSupplier.class); Mockito.when(initializer.get()).thenThrow(new RuntimeException()); LazyAwsCredentialsProvider.create(initializer).close(); Mockito.verify(initializer).close(); } private interface CloseableSupplier extends Supplier<AwsCredentialsProvider>, SdkAutoCloseable {} private interface CloseableCredentialsProvider extends SdkAutoCloseable, AwsCredentialsProvider {} }
1,693
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/internal/Ec2MetadataConfigProviderEndpointResolutionTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.credentials.internal; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import software.amazon.awssdk.core.SdkSystemSetting; @RunWith(Parameterized.class) public class Ec2MetadataConfigProviderEndpointResolutionTest { private static final String EC2_METADATA_SERVICE_URL_IPV4 = "http://169.254.169.254"; private static final String EC2_METADATA_SERVICE_URL_IPV6 = "http://[fd00:ec2::254]"; private static final String ENDPOINT_OVERRIDE = "http://my-custom-endpoint"; @Parameterized.Parameter public TestCase testCase; @Parameterized.Parameters public static Iterable<Object> testCases() { return Arrays.asList( new TestCase().expectedEndpoint(EC2_METADATA_SERVICE_URL_IPV4), new TestCase().endpointMode("ipv6").expectedEndpoint(EC2_METADATA_SERVICE_URL_IPV6), new TestCase().endpointMode("ipv4").expectedEndpoint(EC2_METADATA_SERVICE_URL_IPV4), new TestCase().endpointOverride(ENDPOINT_OVERRIDE).expectedEndpoint(ENDPOINT_OVERRIDE), new TestCase().endpointMode("ipv4").endpointOverride(ENDPOINT_OVERRIDE).expectedEndpoint(ENDPOINT_OVERRIDE), new TestCase().endpointMode("ipv6").endpointOverride(ENDPOINT_OVERRIDE).expectedEndpoint(ENDPOINT_OVERRIDE), new TestCase().endpointMode("ipv99").endpointOverride(ENDPOINT_OVERRIDE).expectedEndpoint(ENDPOINT_OVERRIDE) ); } @Before public void setup() { System.clearProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property()); System.clearProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE.property()); if (testCase.endpointMode != null) { System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE.property(), testCase.endpointMode); } if (testCase.endpointOverride != null) { System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property(), testCase.endpointOverride); } } @Test public void resolvesCorrectEndpoint() { assertThat(Ec2MetadataConfigProvider.builder().build().getEndpoint()).isEqualTo(testCase.expectedEndpoint); } private static class TestCase { private String endpointMode; private String endpointOverride; private String expectedEndpoint; public TestCase endpointMode(String endpointMode) { this.endpointMode = endpointMode; return this; } public TestCase endpointOverride(String endpointOverride) { this.endpointOverride = endpointOverride; return this; } public TestCase expectedEndpoint(String expectedEndpoint) { this.expectedEndpoint = expectedEndpoint; return this; } } }
1,694
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/credentials/internal/ProfileCredentialsUtilsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.credentials.internal; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.io.File; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.List; import java.util.function.Consumer; import java.util.stream.Stream; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.AwsSessionCredentials; import software.amazon.awssdk.auth.credentials.ProcessCredentialsProviderTest; import software.amazon.awssdk.core.checksums.Algorithm; import software.amazon.awssdk.core.checksums.SdkChecksum; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileProperty; import software.amazon.awssdk.utils.StringInputStream; public class ProfileCredentialsUtilsTest { private static String scriptLocation; @BeforeAll public static void setup() { scriptLocation = ProcessCredentialsProviderTest.copyHappyCaseProcessCredentialsScript(); } @AfterAll public static void teardown() { if (scriptLocation != null && !new File(scriptLocation).delete()) { throw new IllegalStateException("Failed to delete file: " + scriptLocation); } } @Test public void roleProfileCanInheritFromAnotherFile() { String sourceProperties = "aws_access_key_id=defaultAccessKey\n" + "aws_secret_access_key=defaultSecretAccessKey"; String childProperties = "source_profile=source\n" + "role_arn=arn:aws:iam::123456789012:role/testRole"; String configSource = "[profile source]\n" + sourceProperties; String credentialsSource = "[source]\n" + sourceProperties; String configChild = "[profile child]\n" + childProperties; String credentialsChild = "[child]\n" + childProperties; ProfileFile sourceProfile = aggregateFileProfiles(configSource, credentialsChild); ProfileFile configProfile = aggregateFileProfiles(configChild, credentialsSource); Consumer<ProfileFile> profileValidator = profileFile -> assertThatThrownBy(new ProfileCredentialsUtils(profileFile, profileFile.profiles().get("child"), profileFile::profile)::credentialsProvider) .hasMessageContaining("the 'sts' service module must be on the class path"); assertThat(sourceProfile).satisfies(profileValidator); assertThat(configProfile).satisfies(profileValidator); } @Test public void roleProfileWithMissingSourceThrowsException() { ProfileFile profileFile = configFile("[profile test]\n" + "source_profile=source\n" + "role_arn=arn:aws:iam::123456789012:role/testRole"); assertThatThrownBy(new ProfileCredentialsUtils(profileFile, profileFile.profile("test") .get(), profileFile::profile)::credentialsProvider) .hasMessageContaining("source profile has no credentials configured."); } @Test public void roleProfileWithSourceThatHasNoCredentialsThrowsExceptionWhenLoadingCredentials() { ProfileFile profiles = configFile("[profile source]\n" + "[profile test]\n" + "source_profile=source\n" + "role_arn=arn:aws:iam::123456789012:role/testRole"); assertThat(profiles.profile("test")).hasValueSatisfying(profile -> { ProfileCredentialsUtils profileCredentialsUtils = new ProfileCredentialsUtils(profiles, profile, profiles::profile); assertThatThrownBy(profileCredentialsUtils::credentialsProvider) .hasMessageContaining("source profile has no credentials configured"); }); } @Test public void profileFileWithRegionLoadsCorrectly() { assertThat(allTypesProfile().profile("profile-with-region")).hasValueSatisfying(profile -> { assertThat(profile.property(ProfileProperty.REGION)).hasValue("us-east-1"); }); } @Test public void profileFileWithStaticCredentialsLoadsCorrectly() { ProfileFile profileFile = allTypesProfile(); assertThat(profileFile.profile("default")).hasValueSatisfying(profile -> { assertThat(profile.name()).isEqualTo("default"); assertThat(profile.property(ProfileProperty.AWS_ACCESS_KEY_ID)).hasValue("defaultAccessKey"); assertThat(profile.toString()).contains("default"); assertThat(profile.property(ProfileProperty.REGION)).isNotPresent(); assertThat(new ProfileCredentialsUtils(profileFile, profile, profileFile::profile).credentialsProvider()).hasValueSatisfying(credentialsProvider -> { assertThat(credentialsProvider.resolveCredentials()).satisfies(credentials -> { assertThat(credentials.accessKeyId()).isEqualTo("defaultAccessKey"); assertThat(credentials.secretAccessKey()).isEqualTo("defaultSecretAccessKey"); }); }); }); } @Test public void profileFileWithSessionCredentialsLoadsCorrectly() { ProfileFile profileFile = allTypesProfile(); assertThat(profileFile.profile("profile-with-session-token")).hasValueSatisfying(profile -> { assertThat(profile.property(ProfileProperty.REGION)).isNotPresent(); assertThat(new ProfileCredentialsUtils(profileFile, profile, profileFile::profile).credentialsProvider()).hasValueSatisfying(credentialsProvider -> { assertThat(credentialsProvider.resolveCredentials()).satisfies(credentials -> { assertThat(credentials).isInstanceOf(AwsSessionCredentials.class); assertThat(credentials.accessKeyId()).isEqualTo("defaultAccessKey"); assertThat(credentials.secretAccessKey()).isEqualTo("defaultSecretAccessKey"); assertThat(((AwsSessionCredentials) credentials).sessionToken()).isEqualTo("awsSessionToken"); }); }); }); } @Test public void profileFileWithProcessCredentialsLoadsCorrectly() { ProfileFile profileFile = allTypesProfile(); assertThat(profileFile.profile("profile-credential-process")).hasValueSatisfying(profile -> { assertThat(profile.property(ProfileProperty.REGION)).isNotPresent(); assertThat(new ProfileCredentialsUtils(profileFile, profile, profileFile::profile).credentialsProvider()).hasValueSatisfying(credentialsProvider -> { assertThat(credentialsProvider.resolveCredentials()).satisfies(credentials -> { assertThat(credentials).isInstanceOf(AwsBasicCredentials.class); assertThat(credentials.accessKeyId()).isEqualTo("defaultAccessKey"); assertThat(credentials.secretAccessKey()).isEqualTo("defaultSecretAccessKey"); }); }); }); } @Test public void profileFileWithAssumeRoleThrowsExceptionWhenRetrievingCredentialsProvider() { ProfileFile profileFile = allTypesProfile(); assertThat(profileFile.profile("profile-with-assume-role")).hasValueSatisfying(profile -> { assertThat(profile.property(ProfileProperty.REGION)).isNotPresent(); ProfileCredentialsUtils profileCredentialsUtils = new ProfileCredentialsUtils(profileFile, profile, profileFile::profile); assertThatThrownBy(profileCredentialsUtils::credentialsProvider).isInstanceOf(IllegalStateException.class); }); } @Test public void profileFileWithCredentialSourceThrowsExceptionWhenRetrievingCredentialsProvider() { ProfileFile profileFile = allTypesProfile(); List<String> profiles = Arrays.asList( "profile-with-container-credential-source", "profile-with-instance-credential-source", "profile-with-environment-credential-source" ); profiles.forEach(profileName -> { assertThat(profileFile.profile(profileName)).hasValueSatisfying(profile -> { assertThat(profile.property(ProfileProperty.REGION)).isNotPresent(); ProfileCredentialsUtils profileCredentialsUtils = new ProfileCredentialsUtils(profileFile, profile, profileFile::profile); assertThatThrownBy(profileCredentialsUtils::credentialsProvider).isInstanceOf(IllegalStateException.class); }); }); } @Test public void profileFileWithCircularDependencyThrowsExceptionWhenResolvingCredentials() { ProfileFile configFile = configFile("[profile source]\n" + "aws_access_key_id=defaultAccessKey\n" + "aws_secret_access_key=defaultSecretAccessKey\n" + "\n" + "[profile test]\n" + "source_profile=test3\n" + "role_arn=arn:aws:iam::123456789012:role/testRole\n" + "\n" + "[profile test2]\n" + "source_profile=test\n" + "role_arn=arn:aws:iam::123456789012:role/testRole2\n" + "\n" + "[profile test3]\n" + "source_profile=test2\n" + "role_arn=arn:aws:iam::123456789012:role/testRole3"); assertThatThrownBy(() -> new ProfileCredentialsUtils(configFile, configFile.profile("test").get(), configFile::profile) .credentialsProvider()) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Invalid profile file: Circular relationship detected with profiles"); } private static Stream<Arguments> roleProfileWithIncompleteSsoRoleNameSSOCredentialsProperties() { return Stream.of( // No sso_region Arguments.of(configFile("[profile test]\n" + "sso_account_id=accountId\n" + "sso_role_name=roleName\n" + "sso_start_url=https//d-abc123.awsapps.com/start"), "Profile property 'sso_region' was not configured for 'test'"), // No sso_account_id Arguments.of(configFile("[profile test]\n" + "sso_region=region\n" + "sso_role_name=roleName\n" + "sso_start_url=https//d-abc123.awsapps.com/start"), "Profile property 'sso_account_id' was not configured for 'test'"), // No sso_start_url Arguments.of(configFile("[profile test]\n" + "sso_account_id=accountId\n" + "sso_region=region\n" + "sso_role_name=roleName\n" + "sso_region=region"), "Profile property 'sso_start_url' was not configured for 'test'"), // No sso_role_name Arguments.of(configFile("[profile test]\n" + "sso_account_id=accountId\n" + "sso_region=region\n" + "sso_start_url=https//d-abc123.awsapps.com/start"), "Profile property 'sso_role_name' was not configured for 'test'"), // sso_session with No sso_account_id Arguments.of(configFile("[profile test]\n" + "sso_session=session\n" + "sso_role_name=roleName"), "Profile property 'sso_account_id' was not configured for 'test'"), // sso_session with No sso_role_name Arguments.of(configFile("[profile test]\n" + "sso_session=session\n" + "sso_account_id=accountId\n" + "sso_start_url=https//d-abc123.awsapps.com/start"), "Profile property 'sso_role_name' was not configured for 'test'"), Arguments.of(configFile("[profile test]\n" + "sso_session=session"), "Profile property 'sso_account_id' was not configured for 'test'") ); } @ParameterizedTest @MethodSource("roleProfileWithIncompleteSsoRoleNameSSOCredentialsProperties") void validateCheckSumValues(ProfileFile profiles, String expectedValue) { assertThat(profiles.profile("test")).hasValueSatisfying(profile -> { ProfileCredentialsUtils profileCredentialsUtils = new ProfileCredentialsUtils(profiles, profile, profiles::profile); assertThatThrownBy(profileCredentialsUtils::credentialsProvider) .hasMessageContaining(expectedValue); }); } @Test public void profileWithBothCredentialSourceAndSourceProfileThrowsException() { ProfileFile configFile = configFile("[profile test]\n" + "source_profile=source\n" + "credential_source=Environment\n" + "role_arn=arn:aws:iam::123456789012:role/testRole3\n" + "\n" + "[profile source]\n" + "aws_access_key_id=defaultAccessKey\n" + "aws_secret_access_key=defaultSecretAccessKey"); assertThatThrownBy(() -> new ProfileCredentialsUtils(configFile, configFile.profile("test").get(), configFile::profile) .credentialsProvider()) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Invalid profile file: profile has both source_profile and credential_source."); } @Test public void profileWithInvalidCredentialSourceThrowsException() { ProfileFile configFile = configFile("[profile test]\n" + "credential_source=foobar\n" + "role_arn=arn:aws:iam::123456789012:role/testRole3"); assertThatThrownBy(() -> new ProfileCredentialsUtils(configFile, configFile.profile("test").get(), configFile::profile) .credentialsProvider()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("foobar is not a valid credential_source"); } private ProfileFile credentialFile(String credentialFile) { return ProfileFile.builder() .content(new StringInputStream(credentialFile)) .type(ProfileFile.Type.CREDENTIALS) .build(); } private ProfileFile aggregateFileProfiles(String configFile, String credentialFile) { return ProfileFile.aggregator() .addFile(credentialFile(credentialFile)) .addFile(configFile(configFile)) .build(); } private ProfileFile allTypesProfile() { return configFile("[default]\n" + "aws_access_key_id = defaultAccessKey\n" + "aws_secret_access_key = defaultSecretAccessKey\n" + "\n" + "[profile profile-with-session-token]\n" + "aws_access_key_id = defaultAccessKey\n" + "aws_secret_access_key = defaultSecretAccessKey\n" + "aws_session_token = awsSessionToken\n" + "\n" + "[profile profile-with-region]\n" + "region = us-east-1\n" + "\n" + "[profile profile-with-assume-role]\n" + "source_profile=default\n" + "role_arn=arn:aws:iam::123456789012:role/testRole\n" + "\n" + "[profile profile-credential-process]\n" + "credential_process=" + scriptLocation +" defaultAccessKey defaultSecretAccessKey\n" + "\n" + "[profile profile-with-container-credential-source]\n" + "credential_source=ecscontainer\n" + "role_arn=arn:aws:iam::123456789012:role/testRole\n" + "\n" + "[profile profile-with-instance-credential-source]\n" + "credential_source=ec2instancemetadata\n" + "role_arn=arn:aws:iam::123456789012:role/testRole\n" + "\n" + "[profile profile-with-environment-credential-source]\n" + "credential_source=environment\n" + "role_arn=arn:aws:iam::123456789012:role/testRole\n"); } private static ProfileFile configFile(String configFile) { return ProfileFile.builder() .content(new StringInputStream(configFile)) .type(ProfileFile.Type.CONFIGURATION) .build(); } }
1,695
0
Create_ds/aws-sdk-java-v2/core/auth/src/it/java/software/amazon/awssdk/auth
Create_ds/aws-sdk-java-v2/core/auth/src/it/java/software/amazon/awssdk/auth/credentials/InstanceProfileCredentialsProviderIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.credentials; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import org.junit.After; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.core.exception.SdkClientException; /** * Unit tests for the InstanceProfileCredentialsProvider. */ public class InstanceProfileCredentialsProviderIntegrationTest { private EC2MetadataServiceMock mockServer; /** Starts up the mock EC2 Instance Metadata Service. */ @Before public void setUp() throws Exception { mockServer = new EC2MetadataServiceMock("/latest/meta-data/iam/security-credentials/"); mockServer.start(); } /** Shuts down the mock EC2 Instance Metadata Service. */ @After public void tearDown() throws Exception { mockServer.stop(); Thread.sleep(1000); } /** Tests that we correctly handle the metadata service returning credentials. */ @Test public void testSessionCredentials() throws Exception { mockServer.setResponseFileName("sessionResponse"); mockServer.setAvailableSecurityCredentials("aws-dr-tools-test"); InstanceProfileCredentialsProvider credentialsProvider = InstanceProfileCredentialsProvider.create(); AwsSessionCredentials credentials = (AwsSessionCredentials) credentialsProvider.resolveCredentials(); assertEquals("ACCESS_KEY_ID", credentials.accessKeyId()); assertEquals("SECRET_ACCESS_KEY", credentials.secretAccessKey()); assertEquals("TOKEN_TOKEN_TOKEN", credentials.sessionToken()); } /** * Tests that we correctly handle the metadata service returning credentials * when multiple instance profiles are available. */ @Test public void testSessionCredentials_MultipleInstanceProfiles() throws Exception { mockServer.setResponseFileName("sessionResponse"); mockServer.setAvailableSecurityCredentials("test-credentials"); AwsSessionCredentials credentials; try (InstanceProfileCredentialsProvider credentialsProvider = InstanceProfileCredentialsProvider.create()) { credentials = (AwsSessionCredentials) credentialsProvider.resolveCredentials(); } assertEquals("ACCESS_KEY_ID", credentials.accessKeyId()); assertEquals("SECRET_ACCESS_KEY", credentials.secretAccessKey()); assertEquals("TOKEN_TOKEN_TOKEN", credentials.sessionToken()); } /** * Tests that we correctly handle when no instance profiles are available * through the metadata service. */ @Test public void testNoInstanceProfiles() throws Exception { mockServer.setResponseFileName("sessionResponse"); mockServer.setAvailableSecurityCredentials(""); try (InstanceProfileCredentialsProvider credentialsProvider = InstanceProfileCredentialsProvider.create()) { try { credentialsProvider.resolveCredentials(); fail("Expected an SdkClientException, but wasn't thrown"); } catch (SdkClientException ace) { assertNotNull(ace.getMessage()); } } } @Test(expected = SdkClientException.class) public void ec2MetadataDisabled_shouldReturnNull() { mockServer.setResponseFileName("sessionResponse"); mockServer.setAvailableSecurityCredentials("test-credentials"); try (InstanceProfileCredentialsProvider credentialsProvider = InstanceProfileCredentialsProvider.create()) { System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_DISABLED.property(), "true"); credentialsProvider.resolveCredentials(); } finally { System.clearProperty(SdkSystemSetting.AWS_EC2_METADATA_DISABLED.property()); } } }
1,696
0
Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token
Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token/signer/SdkTokenExecutionAttribute.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.token.signer; import static software.amazon.awssdk.utils.CompletableFutureUtils.joinLikeSync; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.auth.token.credentials.SdkToken; import software.amazon.awssdk.core.SelectedAuthScheme; import software.amazon.awssdk.core.interceptor.ExecutionAttribute; import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute; import software.amazon.awssdk.http.auth.scheme.BearerAuthScheme; import software.amazon.awssdk.http.auth.signer.BearerHttpSigner; import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeOption; import software.amazon.awssdk.identity.spi.Identity; /** * SdkToken authorizing attributes attached to the execution. * * @deprecated Signer execution attributes have been deprecated in favor of signer properties, set on the auth scheme's signer * options. */ @Deprecated @SdkProtectedApi public final class SdkTokenExecutionAttribute { /** * The token to sign requests using token authorization instead of AWS Credentials. * * @deprecated This is a protected class that is internal to the SDK, so you shouldn't be using it. */ @Deprecated public static final ExecutionAttribute<SdkToken> SDK_TOKEN = ExecutionAttribute.derivedBuilder("SdkToken", SdkToken.class, SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME) .readMapping(SdkTokenExecutionAttribute::sdkTokenReadMapping) .writeMapping(SdkTokenExecutionAttribute::sdkTokenWriteMapping) .build(); private SdkTokenExecutionAttribute() { } private static SdkToken sdkTokenReadMapping(SelectedAuthScheme<?> authScheme) { if (authScheme == null) { return null; } Identity identity = joinLikeSync(authScheme.identity()); if (!(identity instanceof SdkToken)) { return null; } return (SdkToken) identity; } private static <T extends Identity> SelectedAuthScheme<?> sdkTokenWriteMapping(SelectedAuthScheme<T> authScheme, SdkToken token) { if (authScheme == null) { // This is an unusual use-case. // Let's assume they're setting the token so that they can call the signer directly. If that's true, then it // doesn't really matter what we store other than the credentials. return new SelectedAuthScheme<>(CompletableFuture.completedFuture(token), BearerHttpSigner.create(), AuthSchemeOption.builder() .schemeId(BearerAuthScheme.SCHEME_ID) .build()); } return new SelectedAuthScheme<>(CompletableFuture.completedFuture((T) token), authScheme.signer(), authScheme.authSchemeOption()); } }
1,697
0
Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token/signer
Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token/signer/aws/BearerTokenSigner.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.token.signer.aws; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.auth.signer.internal.SignerConstant; import software.amazon.awssdk.auth.signer.params.TokenSignerParams; import software.amazon.awssdk.auth.token.credentials.SdkToken; import software.amazon.awssdk.auth.token.signer.SdkTokenExecutionAttribute; import software.amazon.awssdk.core.CredentialType; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.http.SdkHttpFullRequest; /** * A {@link Signer} that will sign a request with Bearer token authorization. */ @SdkPublicApi public final class BearerTokenSigner implements Signer { private static final String BEARER_LABEL = "Bearer"; public static BearerTokenSigner create() { return new BearerTokenSigner(); } @Override public CredentialType credentialType() { return CredentialType.TOKEN; } /** * Signs the request by adding an 'Authorization' header containing the string value of the token * in accordance with RFC 6750, section 2.1. * * @param request The request to sign * @param signerParams Contains the attributes required for signing the request * * @return The signed request. */ public SdkHttpFullRequest sign(SdkHttpFullRequest request, TokenSignerParams signerParams) { return doSign(request, signerParams); } /** * Signs the request by adding an 'Authorization' header containing the string value of the token * in accordance with RFC 6750, section 2.1. * * @param request The request to sign * @param executionAttributes Contains the execution attributes required for signing the request * * @return The signed request. */ @Override public SdkHttpFullRequest sign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes) { SdkToken token = executionAttributes.getAttribute(SdkTokenExecutionAttribute.SDK_TOKEN); return doSign(request, TokenSignerParams.builder().token(token).build()); } private SdkHttpFullRequest doSign(SdkHttpFullRequest request, TokenSignerParams signerParams) { return request.toBuilder() .putHeader(SignerConstant.AUTHORIZATION, buildAuthorizationHeader(signerParams.token())) .build(); } private String buildAuthorizationHeader(SdkToken token) { return String.format("%s %s", BEARER_LABEL, token.token()); } }
1,698
0
Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token
Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token/internal/ProfileTokenProviderLoader.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.token.internal; import java.lang.reflect.InvocationTargetException; import java.util.Arrays; import java.util.Objects; import java.util.Optional; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.auth.token.credentials.ChildProfileTokenProviderFactory; import software.amazon.awssdk.auth.token.credentials.SdkTokenProvider; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.internal.util.ClassLoaderHelper; import software.amazon.awssdk.profiles.Profile; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileProperty; import software.amazon.awssdk.profiles.internal.ProfileSection; import software.amazon.awssdk.utils.Lazy; import software.amazon.awssdk.utils.Validate; /** * Utility class to load SSO Token Providers. */ @SdkInternalApi public final class ProfileTokenProviderLoader { private static final String SSO_OIDC_TOKEN_PROVIDER_FACTORY = "software.amazon.awssdk.services.ssooidc.SsoOidcProfileTokenProviderFactory"; private final Supplier<ProfileFile> profileFileSupplier; private final String profileName; private volatile ProfileFile currentProfileFile; private volatile SdkTokenProvider currentTokenProvider; private final Lazy<ChildProfileTokenProviderFactory> factory; public ProfileTokenProviderLoader(Supplier<ProfileFile> profileFile, String profileName) { this.profileFileSupplier = Validate.paramNotNull(profileFile, "profileFile"); this.profileName = Validate.paramNotNull(profileName, "profileName"); this.factory = new Lazy<>(this::ssoTokenProviderFactory); } /** * Retrieve the token provider for which this profile has been configured, if available. */ public Optional<SdkTokenProvider> tokenProvider() { return Optional.ofNullable(ssoProfileCredentialsProvider()); } /** * Create the SSO credentials provider based on the related profile properties. */ private SdkTokenProvider ssoProfileCredentialsProvider() { return () -> ssoProfileCredentialsProvider(profileFileSupplier, profileName).resolveToken(); } private SdkTokenProvider ssoProfileCredentialsProvider(ProfileFile profileFile, Profile profile) { String profileSsoSectionName = profileSsoSectionName(profile); Profile ssoProfile = ssoProfile(profileFile, profileSsoSectionName); validateRequiredProperties(ssoProfile, ProfileProperty.SSO_REGION, ProfileProperty.SSO_START_URL); return factory.getValue().create(profileFile, profile); } private SdkTokenProvider ssoProfileCredentialsProvider(Supplier<ProfileFile> profileFile, String profileName) { ProfileFile profileFileInstance = profileFile.get(); if (!Objects.equals(profileFileInstance, currentProfileFile)) { synchronized (this) { if (!Objects.equals(profileFileInstance, currentProfileFile)) { Profile profileInstance = resolveProfile(profileFileInstance, profileName); currentProfileFile = profileFileInstance; currentTokenProvider = ssoProfileCredentialsProvider(profileFileInstance, profileInstance); } } } return currentTokenProvider; } private Profile resolveProfile(ProfileFile profileFile, String profileName) { return profileFile.profile(profileName) .orElseThrow(() -> { String errorMessage = String.format("Profile file contained no information for profile '%s': %s", profileName, profileFile); return SdkClientException.builder().message(errorMessage).build(); }); } private String profileSsoSectionName(Profile profile) { return Optional.ofNullable(profile) .flatMap(p -> p.property(ProfileSection.SSO_SESSION.getPropertyKeyName())) .orElseThrow(() -> new IllegalArgumentException( "Profile " + profileName + " does not have sso_session property")); } private Profile ssoProfile(ProfileFile profileFile, String profileSsoSectionName) { return profileFile.getSection(ProfileSection.SSO_SESSION.getSectionTitle(), profileSsoSectionName) .orElseThrow(() -> new IllegalArgumentException( "Sso-session section not found with sso-session title " + profileSsoSectionName)); } /** * Require that the provided properties are configured in this profile. */ private void validateRequiredProperties(Profile ssoProfile, String... requiredProperties) { Arrays.stream(requiredProperties) .forEach(p -> Validate.isTrue(ssoProfile.properties().containsKey(p), "Property '%s' was not configured for profile '%s'.", p, profileName)); } /** * Load the factory that can be used to create the SSO token provider, assuming it is on the classpath. */ private ChildProfileTokenProviderFactory ssoTokenProviderFactory() { try { Class<?> ssoOidcTokenProviderFactory = ClassLoaderHelper.loadClass(SSO_OIDC_TOKEN_PROVIDER_FACTORY, getClass()); return (ChildProfileTokenProviderFactory) ssoOidcTokenProviderFactory.getConstructor().newInstance(); } catch (ClassNotFoundException e) { throw new IllegalStateException("To use SSO OIDC related properties in the '" + profileName + "' profile, " + "the 'ssooidc' service module must be on the class path.", e); } catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e) { throw new IllegalStateException("Failed to create the '%s" + profileName + "' token provider factory.", e); } } }
1,699