index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/handlers/ExceptionTranslationInterceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.handlers; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.exception.AwsErrorDetails; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.services.s3.model.HeadBucketRequest; import software.amazon.awssdk.services.s3.model.HeadObjectRequest; import software.amazon.awssdk.services.s3.model.NoSuchBucketException; import software.amazon.awssdk.services.s3.model.NoSuchKeyException; import software.amazon.awssdk.services.s3.model.S3Exception; /** * Translate S3Exception for the API calls that do not contain the detailed error code. */ @SdkInternalApi public final class ExceptionTranslationInterceptor implements ExecutionInterceptor { @Override public Throwable modifyException(Context.FailedExecution context, ExecutionAttributes executionAttributes) { if (!isS3Exception404(context.exception()) || !isHeadRequest(context.request())) { return context.exception(); } String message = context.exception().getMessage(); S3Exception exception = (S3Exception) (context.exception()); String requestIdFromHeader = exception.awsErrorDetails() .sdkHttpResponse() .firstMatchingHeader("x-amz-request-id") .orElse(null); String requestId = Optional.ofNullable(exception.requestId()).orElse(requestIdFromHeader); AwsErrorDetails errorDetails = exception.awsErrorDetails(); if (context.request() instanceof HeadObjectRequest) { return NoSuchKeyException.builder() .awsErrorDetails(fillErrorDetails(errorDetails, "NoSuchKey", "The specified key does not exist.")) .statusCode(404) .requestId(requestId) .message(message) .build(); } if (context.request() instanceof HeadBucketRequest) { return NoSuchBucketException.builder() .awsErrorDetails(fillErrorDetails(errorDetails, "NoSuchBucket", "The specified bucket does not exist.")) .statusCode(404) .requestId(requestId) .message(message) .build(); } return context.exception(); } private AwsErrorDetails fillErrorDetails(AwsErrorDetails original, String errorCode, String errorMessage) { return original.toBuilder().errorMessage(errorMessage).errorCode(errorCode).build(); } private boolean isHeadRequest(SdkRequest request) { return (request instanceof HeadObjectRequest || request instanceof HeadBucketRequest); } private boolean isS3Exception404(Throwable thrown) { if (!(thrown instanceof S3Exception)) { return false; } return ((S3Exception) thrown).statusCode() == 404; } }
4,600
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/settingproviders/DisableMultiRegionProviderChain.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.settingproviders; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileFileSystemSetting; import software.amazon.awssdk.utils.Logger; /** * {@link DisableMultiRegionProvider} implementation that chains together multiple disable multi-region providers. */ @SdkInternalApi public final class DisableMultiRegionProviderChain implements DisableMultiRegionProvider { private static final Logger log = Logger.loggerFor(DisableMultiRegionProvider.class); private static final String SETTING = "disableMultiRegion"; private final List<DisableMultiRegionProvider> providers; private DisableMultiRegionProviderChain(List<DisableMultiRegionProvider> providers) { this.providers = providers; } /** * Creates a default {@link DisableMultiRegionProviderChain}. * * <p> * AWS disable multi-region provider that looks for the disable flag in this order: * * <ol> * <li>Check if 'aws.s3DisableMultiRegionAccessPoints' system property is set.</li> * <li>Check if 'AWS_S3_DISABLE_MULTIREGION_ACCESS_POINTS' environment is set.</li> * <li>Check if 's3_disable_multiregion_access_points' profile file configuration is set.</li> * </ol> */ public static DisableMultiRegionProviderChain create() { return create(ProfileFile::defaultProfileFile, ProfileFileSystemSetting.AWS_PROFILE.getStringValueOrThrow()); } public static DisableMultiRegionProviderChain create(ProfileFile profileFile, String profileName) { return new DisableMultiRegionProviderChain(Arrays.asList( SystemsSettingsDisableMultiRegionProvider.create(), ProfileDisableMultiRegionProvider.create(profileFile, profileName))); } public static DisableMultiRegionProviderChain create(Supplier<ProfileFile> profileFile, String profileName) { return new DisableMultiRegionProviderChain(Arrays.asList( SystemsSettingsDisableMultiRegionProvider.create(), ProfileDisableMultiRegionProvider.create(profileFile, profileName))); } @Override public Optional<Boolean> resolve() { for (DisableMultiRegionProvider provider : providers) { try { Optional<Boolean> value = provider.resolve(); if (value.isPresent()) { return value; } } catch (Exception ex) { log.warn(() -> "Failed to retrieve " + SETTING + " from " + provider, ex); } } return Optional.empty(); } }
4,601
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/settingproviders/ProfileDisableMultiRegionProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.settingproviders; import java.util.Optional; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileFileSystemSetting; import software.amazon.awssdk.utils.StringUtils; /** * Loads configuration from the {@link ProfileFile#defaultProfileFile()} using the default profile name. */ @SdkInternalApi public final class ProfileDisableMultiRegionProvider implements DisableMultiRegionProvider { /** * Property name for specifying whether or not multi-region should be disabled. */ private static final String AWS_DISABLE_MULTI_REGION = "s3_disable_multiregion_access_points"; private final Supplier<ProfileFile> profileFile; private final String profileName; private ProfileDisableMultiRegionProvider(Supplier<ProfileFile> profileFile, String profileName) { this.profileFile = profileFile; this.profileName = profileName; } public static ProfileDisableMultiRegionProvider create() { return new ProfileDisableMultiRegionProvider(ProfileFile::defaultProfileFile, ProfileFileSystemSetting.AWS_PROFILE.getStringValueOrThrow()); } public static ProfileDisableMultiRegionProvider create(ProfileFile profileFile, String profileName) { return new ProfileDisableMultiRegionProvider(() -> profileFile, profileName); } public static ProfileDisableMultiRegionProvider create(Supplier<ProfileFile> profileFile, String profileName) { return new ProfileDisableMultiRegionProvider(profileFile, profileName); } @Override public Optional<Boolean> resolve() { return profileFile.get() .profile(profileName) .map(p -> p.properties().get(AWS_DISABLE_MULTI_REGION)) .map(StringUtils::safeStringToBoolean); } }
4,602
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/settingproviders/ProfileUseArnRegionProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.settingproviders; import java.util.Optional; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileFileSystemSetting; import software.amazon.awssdk.utils.StringUtils; /** * Loads useArnRegion configuration from the {@link ProfileFile#defaultProfileFile()} using the default profile name. */ @SdkInternalApi public final class ProfileUseArnRegionProvider implements UseArnRegionProvider { /** * Property name for specifying whether or not to use arn region should be enabled. */ private static final String AWS_USE_ARN_REGION = "s3_use_arn_region"; private final Supplier<ProfileFile> profileFile; private final String profileName; private ProfileUseArnRegionProvider(Supplier<ProfileFile> profileFile, String profileName) { this.profileFile = profileFile; this.profileName = profileName; } public static ProfileUseArnRegionProvider create() { return new ProfileUseArnRegionProvider(ProfileFile::defaultProfileFile, ProfileFileSystemSetting.AWS_PROFILE.getStringValueOrThrow()); } public static ProfileUseArnRegionProvider create(ProfileFile profileFile, String profileName) { return new ProfileUseArnRegionProvider(() -> profileFile, profileName); } public static ProfileUseArnRegionProvider create(Supplier<ProfileFile> profileFile, String profileName) { return new ProfileUseArnRegionProvider(profileFile, profileName); } @Override public Optional<Boolean> resolveUseArnRegion() { return profileFile.get() .profile(profileName) .map(p -> p.properties().get(AWS_USE_ARN_REGION)) .map(StringUtils::safeStringToBoolean); } }
4,603
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/settingproviders/UseArnRegionProviderChain.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.settingproviders; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileFileSystemSetting; import software.amazon.awssdk.utils.Logger; /** * {@link UseArnRegionProvider} implementation that chains together multiple useArnRegion providers. */ @SdkInternalApi public final class UseArnRegionProviderChain implements UseArnRegionProvider { private static final Logger log = Logger.loggerFor(UseArnRegionProvider.class); private final List<UseArnRegionProvider> providers; private UseArnRegionProviderChain(List<UseArnRegionProvider> providers) { this.providers = providers; } /** * Creates a default {@link UseArnRegionProviderChain}. * * <p> * AWS use arn region provider that looks for the useArnRegion in this order: * * <ol> * <li>Check if 'aws.s3UseArnRegion' system property is set.</li> * <li>Check if 'AWS_USE_ARN_REGION' environment variable is set.</li> * <li>Check if 's3_use_arn_region' profile file configuration is set.</li> * </ol> */ public static UseArnRegionProviderChain create() { return create(ProfileFile::defaultProfileFile, ProfileFileSystemSetting.AWS_PROFILE.getStringValueOrThrow()); } public static UseArnRegionProviderChain create(ProfileFile profileFile, String profileName) { return new UseArnRegionProviderChain(Arrays.asList(SystemsSettingsUseArnRegionProvider.create(), ProfileUseArnRegionProvider.create(profileFile, profileName))); } public static UseArnRegionProviderChain create(Supplier<ProfileFile> profileFile, String profileName) { return new UseArnRegionProviderChain(Arrays.asList(SystemsSettingsUseArnRegionProvider.create(), ProfileUseArnRegionProvider.create(profileFile, profileName))); } @Override public Optional<Boolean> resolveUseArnRegion() { for (UseArnRegionProvider provider : providers) { try { Optional<Boolean> useArnRegion = provider.resolveUseArnRegion(); if (useArnRegion.isPresent()) { return useArnRegion; } } catch (Exception ex) { log.warn(() -> "Failed to retrieve useArnRegion from " + provider, ex); } } return Optional.empty(); } }
4,604
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/settingproviders/SystemsSettingsDisableMultiRegionProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.settingproviders; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.services.s3.S3SystemSetting; /** * {@link DisableMultiRegionProvider} implementation that loads configuration from system properties * and environment variables. */ @SdkInternalApi public final class SystemsSettingsDisableMultiRegionProvider implements DisableMultiRegionProvider { private SystemsSettingsDisableMultiRegionProvider() { } public static SystemsSettingsDisableMultiRegionProvider create() { return new SystemsSettingsDisableMultiRegionProvider(); } @Override public Optional<Boolean> resolve() { return S3SystemSetting.AWS_S3_DISABLE_MULTIREGION_ACCESS_POINTS.getBooleanValue(); } }
4,605
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/settingproviders/DisableMultiRegionProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.settingproviders; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; /** * Interface for loading disable multi-region configuration. */ @FunctionalInterface @SdkInternalApi public interface DisableMultiRegionProvider { /** * @return whether multi-region is disabled, or empty if it is not configured. */ Optional<Boolean> resolve(); }
4,606
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/settingproviders/UseArnRegionProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.settingproviders; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; /** * Interface for loading useArnRegion configuration. */ @FunctionalInterface @SdkInternalApi public interface UseArnRegionProvider { /** * @return whether use-arn-region is enabled, or empty if it is not configured. */ Optional<Boolean> resolveUseArnRegion(); }
4,607
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/settingproviders/SystemsSettingsUseArnRegionProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.settingproviders; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.services.s3.S3SystemSetting; /** * {@link UseArnRegionProvider} implementation that loads userArnRegion configuration from system properties * and environment variables. */ @SdkInternalApi public final class SystemsSettingsUseArnRegionProvider implements UseArnRegionProvider { private SystemsSettingsUseArnRegionProvider() { } public static SystemsSettingsUseArnRegionProvider create() { return new SystemsSettingsUseArnRegionProvider(); } @Override public Optional<Boolean> resolveUseArnRegion() { return S3SystemSetting.AWS_S3_USE_ARN_REGION.getBooleanValue(); } }
4,608
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/crossregion/S3CrossRegionSyncClient.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.crossregion; import static software.amazon.awssdk.services.s3.internal.crossregion.utils.CrossRegionUtils.getBucketRegionFromException; import static software.amazon.awssdk.services.s3.internal.crossregion.utils.CrossRegionUtils.isS3RedirectException; import static software.amazon.awssdk.services.s3.internal.crossregion.utils.CrossRegionUtils.requestWithDecoratedEndpointProvider; import static software.amazon.awssdk.services.s3.internal.crossregion.utils.CrossRegionUtils.updateUserAgentInConfig; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.DelegatingS3Client; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.HeadBucketRequest; import software.amazon.awssdk.services.s3.model.S3Exception; import software.amazon.awssdk.services.s3.model.S3Request; /** * Decorator S3 Sync client that will fetch the region name whenever there is Redirect 301 error due to cross region bucket * access. */ @SdkInternalApi public final class S3CrossRegionSyncClient extends DelegatingS3Client { private final Map<String, Region> bucketToRegionCache = new ConcurrentHashMap<>(); public S3CrossRegionSyncClient(S3Client s3Client) { super(s3Client); } private static <T extends S3Request> Optional<String> bucketNameFromRequest(T request) { return request.getValueForField("Bucket", String.class); } @Override protected <T extends S3Request, ReturnT> ReturnT invokeOperation(T request, Function<T, ReturnT> operation) { Optional<String> bucketRequest = bucketNameFromRequest(request); AwsRequestOverrideConfiguration overrideConfiguration = updateUserAgentInConfig(request); T userAgentUpdatedRequest = (T) request.toBuilder().overrideConfiguration(overrideConfiguration).build(); if (!bucketRequest.isPresent()) { return operation.apply(userAgentUpdatedRequest); } String bucketName = bucketRequest.get(); try { if (bucketToRegionCache.containsKey(bucketName)) { return operation.apply( requestWithDecoratedEndpointProvider(userAgentUpdatedRequest, () -> bucketToRegionCache.get(bucketName), serviceClientConfiguration().endpointProvider().get())); } return operation.apply(userAgentUpdatedRequest); } catch (S3Exception exception) { if (isS3RedirectException(exception)) { updateCacheFromRedirectException(exception, bucketName); return operation.apply( requestWithDecoratedEndpointProvider( userAgentUpdatedRequest, () -> bucketToRegionCache.computeIfAbsent(bucketName, this::fetchBucketRegion), serviceClientConfiguration().endpointProvider().get())); } throw exception; } } private void updateCacheFromRedirectException(S3Exception exception, String bucketName) { Optional<String> regionStr = getBucketRegionFromException(exception); // If redirected, clear previous values due to region change. bucketToRegionCache.remove(bucketName); regionStr.ifPresent(region -> bucketToRegionCache.put(bucketName, Region.of(region))); } private Region fetchBucketRegion(String bucketName) { try { ((S3Client) delegate()).headBucket(HeadBucketRequest.builder().bucket(bucketName).build()); } catch (S3Exception exception) { if (isS3RedirectException(exception)) { return Region.of(getBucketRegionFromException(exception).orElseThrow(() -> exception)); } throw exception; } return null; } }
4,609
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/crossregion/S3CrossRegionAsyncClient.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.crossregion; import static software.amazon.awssdk.services.s3.internal.crossregion.utils.CrossRegionUtils.getBucketRegionFromException; import static software.amazon.awssdk.services.s3.internal.crossregion.utils.CrossRegionUtils.isS3RedirectException; import static software.amazon.awssdk.services.s3.internal.crossregion.utils.CrossRegionUtils.requestWithDecoratedEndpointProvider; import static software.amazon.awssdk.services.s3.internal.crossregion.utils.CrossRegionUtils.updateUserAgentInConfig; import java.util.Map; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiConsumer; import java.util.function.Function; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.DelegatingS3AsyncClient; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.model.S3Exception; import software.amazon.awssdk.services.s3.model.S3Request; import software.amazon.awssdk.utils.CompletableFutureUtils; @SdkInternalApi public final class S3CrossRegionAsyncClient extends DelegatingS3AsyncClient { private final Map<String, Region> bucketToRegionCache = new ConcurrentHashMap<>(); public S3CrossRegionAsyncClient(S3AsyncClient s3Client) { super(s3Client); } @Override protected <T extends S3Request, ReturnT> CompletableFuture<ReturnT> invokeOperation( T request, Function<T, CompletableFuture<ReturnT>> operation) { Optional<String> bucket = request.getValueForField("Bucket", String.class); AwsRequestOverrideConfiguration overrideConfiguration = updateUserAgentInConfig(request); T userAgentUpdatedRequest = (T) request.toBuilder().overrideConfiguration(overrideConfiguration).build(); if (!bucket.isPresent()) { return operation.apply(userAgentUpdatedRequest); } String bucketName = bucket.get(); CompletableFuture<ReturnT> returnFuture = new CompletableFuture<>(); CompletableFuture<ReturnT> apiOperationFuture = bucketToRegionCache.containsKey(bucketName) ? operation.apply( requestWithDecoratedEndpointProvider( userAgentUpdatedRequest, () -> bucketToRegionCache.get(bucketName), serviceClientConfiguration().endpointProvider().get() ) ) : operation.apply(userAgentUpdatedRequest); apiOperationFuture.whenComplete(redirectToCrossRegionIfRedirectException(operation, userAgentUpdatedRequest, bucketName, returnFuture)); return returnFuture; } private <T extends S3Request, ReturnT> BiConsumer<ReturnT, Throwable> redirectToCrossRegionIfRedirectException( Function<T, CompletableFuture<ReturnT>> operation, T userAgentUpdatedRequest, String bucketName, CompletableFuture<ReturnT> returnFuture) { return (response, throwable) -> { if (throwable != null) { if (isS3RedirectException(throwable)) { bucketToRegionCache.remove(bucketName); requestWithCrossRegion(userAgentUpdatedRequest, operation, bucketName, returnFuture, throwable); } else { returnFuture.completeExceptionally(throwable); } } else { returnFuture.complete(response); } }; } private <T extends S3Request, ReturnT> void requestWithCrossRegion(T request, Function<T, CompletableFuture<ReturnT>> operation, String bucketName, CompletableFuture<ReturnT> returnFuture, Throwable throwable) { Optional<String> bucketRegionFromException = getBucketRegionFromException((S3Exception) throwable.getCause()); if (bucketRegionFromException.isPresent()) { sendRequestWithRightRegion(request, operation, bucketName, returnFuture, bucketRegionFromException.get()); } else { fetchRegionAndSendRequest(request, operation, bucketName, returnFuture); } } private <T extends S3Request, ReturnT> void fetchRegionAndSendRequest(T request, Function<T, CompletableFuture<ReturnT>> operation, String bucketName, CompletableFuture<ReturnT> returnFuture) { // // TODO: Need to change codegen of Delegating Client to avoid the cast, have taken a backlog item to fix this. ((S3AsyncClient) delegate()).headBucket(b -> b.bucket(bucketName)).whenComplete((response, throwable) -> { if (throwable != null) { if (isS3RedirectException(throwable)) { bucketToRegionCache.remove(bucketName); Optional<String> bucketRegion = getBucketRegionFromException((S3Exception) throwable.getCause()); if (bucketRegion.isPresent()) { sendRequestWithRightRegion(request, operation, bucketName, returnFuture, bucketRegion.get()); } else { returnFuture.completeExceptionally(throwable); } } else { returnFuture.completeExceptionally(throwable); } } }); } private <T extends S3Request, ReturnT> void sendRequestWithRightRegion(T request, Function<T, CompletableFuture<ReturnT>> operation, String bucketName, CompletableFuture<ReturnT> returnFuture, String region) { bucketToRegionCache.put(bucketName, Region.of(region)); CompletableFuture<ReturnT> newFuture = operation.apply( requestWithDecoratedEndpointProvider(request, () -> Region.of(region), serviceClientConfiguration().endpointProvider().get())); CompletableFutureUtils.forwardResultTo(newFuture, returnFuture); CompletableFutureUtils.forwardExceptionTo(returnFuture, newFuture); } }
4,610
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/crossregion
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/crossregion/endpointprovider/BucketEndpointProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.crossregion.endpointprovider; import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.endpoints.Endpoint; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.endpoints.S3EndpointParams; import software.amazon.awssdk.services.s3.endpoints.S3EndpointProvider; /** * Decorator S3EndpointProvider which updates the region with the one that is supplied during its instantiation. */ @SdkInternalApi public class BucketEndpointProvider implements S3EndpointProvider { private final S3EndpointProvider delegateEndPointProvider; private final Supplier<Region> regionSupplier; private BucketEndpointProvider(S3EndpointProvider delegateEndPointProvider, Supplier<Region> regionSupplier) { this.delegateEndPointProvider = delegateEndPointProvider; this.regionSupplier = regionSupplier; } public static BucketEndpointProvider create(S3EndpointProvider delegateEndPointProvider, Supplier<Region> regionSupplier) { return new BucketEndpointProvider(delegateEndPointProvider, regionSupplier); } @Override public CompletableFuture<Endpoint> resolveEndpoint(S3EndpointParams endpointParams) { Region crossRegion = regionSupplier.get(); return delegateEndPointProvider.resolveEndpoint( crossRegion != null ? endpointParams.copy(c -> c.region(crossRegion)) : endpointParams); } }
4,611
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/crossregion
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/crossregion/utils/CrossRegionUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.crossregion.utils; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletionException; import java.util.function.Consumer; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.awscore.exception.AwsErrorDetails; import software.amazon.awssdk.core.ApiName; import software.amazon.awssdk.endpoints.EndpointProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.endpoints.S3EndpointProvider; import software.amazon.awssdk.services.s3.internal.crossregion.endpointprovider.BucketEndpointProvider; import software.amazon.awssdk.services.s3.model.S3Exception; import software.amazon.awssdk.services.s3.model.S3Request; @SdkInternalApi public final class CrossRegionUtils { public static final int REDIRECT_STATUS_CODE = 301; public static final int TEMPORARY_REDIRECT_STATUS_CODE = 307; public static final String AMZ_BUCKET_REGION_HEADER = "x-amz-bucket-region"; private static final List<Integer> REDIRECT_STATUS_CODES = Arrays.asList(REDIRECT_STATUS_CODE, TEMPORARY_REDIRECT_STATUS_CODE); private static final List<String> REDIRECT_ERROR_CODES = Collections.singletonList("AuthorizationHeaderMalformed"); private static final ApiName API_NAME = ApiName.builder().version("cross-region").name("hll").build(); private static final Consumer<AwsRequestOverrideConfiguration.Builder> USER_AGENT_APPLIER = b -> b.addApiName(API_NAME); private CrossRegionUtils() { } public static Optional<String> getBucketRegionFromException(S3Exception exception) { return exception.awsErrorDetails() .sdkHttpResponse() .firstMatchingHeader(AMZ_BUCKET_REGION_HEADER); } public static boolean isS3RedirectException(Throwable exception) { Throwable exceptionToBeChecked = exception instanceof CompletionException ? exception.getCause() : exception; return exceptionToBeChecked instanceof S3Exception && isRedirectError((S3Exception) exceptionToBeChecked); } private static boolean isRedirectError(S3Exception exceptionToBeChecked) { if (REDIRECT_STATUS_CODES.stream().anyMatch(status -> status.equals(exceptionToBeChecked.statusCode()))) { return true; } if (getBucketRegionFromException(exceptionToBeChecked).isPresent()) { return true; } AwsErrorDetails awsErrorDetails = exceptionToBeChecked.awsErrorDetails(); return awsErrorDetails != null && REDIRECT_ERROR_CODES.stream().anyMatch(code -> code.equals(awsErrorDetails.errorCode())); } @SuppressWarnings("unchecked") public static <T extends S3Request> T requestWithDecoratedEndpointProvider(T request, Supplier<Region> regionSupplier, EndpointProvider clientEndpointProvider) { AwsRequestOverrideConfiguration requestOverrideConfig = request.overrideConfiguration().orElseGet(() -> AwsRequestOverrideConfiguration.builder().build()); S3EndpointProvider delegateEndpointProvider = (S3EndpointProvider) requestOverrideConfig.endpointProvider() .orElse(clientEndpointProvider); return (T) request.toBuilder() .overrideConfiguration( requestOverrideConfig.toBuilder() .endpointProvider( BucketEndpointProvider.create(delegateEndpointProvider, regionSupplier)) .build()) .build(); } public static <T extends S3Request> AwsRequestOverrideConfiguration updateUserAgentInConfig(T request) { return request.overrideConfiguration().map(c -> c.toBuilder() .applyMutation(USER_AGENT_APPLIER) .build()) .orElseGet(() -> AwsRequestOverrideConfiguration.builder() .applyMutation(USER_AGENT_APPLIER) .build()); } }
4,612
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/checksums/ChecksumsEnabledValidator.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.checksums; import static software.amazon.awssdk.services.s3.checksums.ChecksumConstant.CHECKSUM_ENABLED_RESPONSE_HEADER; import static software.amazon.awssdk.services.s3.checksums.ChecksumConstant.ENABLE_MD5_CHECKSUM_HEADER_VALUE; import static software.amazon.awssdk.services.s3.checksums.ChecksumConstant.SERVER_SIDE_CUSTOMER_ENCRYPTION_HEADER; import static software.amazon.awssdk.services.s3.checksums.ChecksumConstant.SERVER_SIDE_ENCRYPTION_HEADER; import static software.amazon.awssdk.services.s3.model.ServerSideEncryption.AWS_KMS; import java.util.Arrays; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute; import software.amazon.awssdk.core.ClientType; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.checksums.ChecksumSpecs; import software.amazon.awssdk.core.checksums.SdkChecksum; import software.amazon.awssdk.core.exception.RetryableException; 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.http.SdkHttpHeaders; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.S3Configuration; import software.amazon.awssdk.services.s3.internal.handlers.AsyncChecksumValidationInterceptor; import software.amazon.awssdk.services.s3.internal.handlers.SyncChecksumValidationInterceptor; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.model.PutObjectResponse; import software.amazon.awssdk.utils.BinaryUtils; import software.amazon.awssdk.utils.StringUtils; import software.amazon.awssdk.utils.internal.Base16Lower; /** * Class used by {@link SyncChecksumValidationInterceptor} and * {@link AsyncChecksumValidationInterceptor} to determine if trailing checksums * should be enabled for a given request. */ @SdkInternalApi public final class ChecksumsEnabledValidator { public static final ExecutionAttribute<SdkChecksum> CHECKSUM = new ExecutionAttribute<>("checksum"); private ChecksumsEnabledValidator() { } /** * Checks if trailing checksum is enabled for {@link S3Client#getObject(GetObjectRequest)} per request. * * @param request the request * @param executionAttributes the executionAttributes * @return true if trailing checksums is enabled, false otherwise */ public static boolean getObjectChecksumEnabledPerRequest(SdkRequest request, ExecutionAttributes executionAttributes) { return request instanceof GetObjectRequest && checksumEnabledPerConfig(executionAttributes); } /** * Checks if trailing checksum is enabled for {@link S3Client#getObject(GetObjectRequest)} per response. * * @param request the request * @param responseHeaders the response headers * @return true if trailing checksums is enabled, false otherwise */ public static boolean getObjectChecksumEnabledPerResponse(SdkRequest request, SdkHttpHeaders responseHeaders) { return request instanceof GetObjectRequest && checksumEnabledPerResponse(responseHeaders); } /** * Validates that checksums should be enabled based on {@link ClientType} and the presence * or S3 specific headers. * * @param expectedClientType - The expected client type for enabling checksums * @param executionAttributes - {@link ExecutionAttributes} to determine the actual client type * @return If trailing checksums should be enabled for this request. */ public static boolean shouldRecordChecksum(SdkRequest sdkRequest, ClientType expectedClientType, ExecutionAttributes executionAttributes, SdkHttpRequest httpRequest) { if (!(sdkRequest instanceof PutObjectRequest)) { return false; } ClientType actualClientType = executionAttributes.getAttribute(SdkExecutionAttribute.CLIENT_TYPE); if (expectedClientType != actualClientType) { return false; } if (hasServerSideEncryptionHeader(httpRequest)) { return false; } //Checksum validation is done at Service side when HTTP Checksum algorithm attribute is set. if (isHttpCheckSumValidationEnabled(executionAttributes)) { return false; } return checksumEnabledPerConfig(executionAttributes); } private static boolean isHttpCheckSumValidationEnabled(ExecutionAttributes executionAttributes) { Optional<ChecksumSpecs> resolvedChecksum = executionAttributes.getOptionalAttribute(SdkExecutionAttribute.RESOLVED_CHECKSUM_SPECS); if (resolvedChecksum.isPresent()) { ChecksumSpecs checksumSpecs = resolvedChecksum.get(); return checksumSpecs.algorithm() != null; } return false; } public static boolean responseChecksumIsValid(SdkHttpResponse httpResponse) { return !hasServerSideEncryptionHeader(httpResponse); } private static boolean hasServerSideEncryptionHeader(SdkHttpHeaders httpRequest) { // S3 doesn't support trailing checksums for customer encryption if (httpRequest.firstMatchingHeader(SERVER_SIDE_CUSTOMER_ENCRYPTION_HEADER).isPresent()) { return true; } // S3 doesn't support trailing checksums for KMS encrypted objects if (httpRequest.firstMatchingHeader(SERVER_SIDE_ENCRYPTION_HEADER) .filter(h -> h.contains(AWS_KMS.toString())) .isPresent()) { return true; } return false; } /** * Client side validation for {@link PutObjectRequest} * * @param response the response * @param executionAttributes the execution attributes */ public static void validatePutObjectChecksum(PutObjectResponse response, ExecutionAttributes executionAttributes) { SdkChecksum checksum = executionAttributes.getAttribute(CHECKSUM); if (response.eTag() != null) { String contentMd5 = BinaryUtils.toBase64(checksum.getChecksumBytes()); byte[] digest = BinaryUtils.fromBase64(contentMd5); byte[] ssHash = Base16Lower.decode(StringUtils.replace(response.eTag(), "\"", "")); if (!Arrays.equals(digest, ssHash)) { throw RetryableException.create( String.format("Data read has a different checksum than expected. Was 0x%s, but expected 0x%s. " + "This commonly means that the data was corrupted between the client and " + "service. Note: Despite this error, the upload still completed and was persisted in S3.", BinaryUtils.toHex(digest), BinaryUtils.toHex(ssHash))); } } } /** * Check the response header to see if the trailing checksum is enabled. * * @param responseHeaders the SdkHttpHeaders * @return true if the trailing checksum is present in the header, false otherwise. */ private static boolean checksumEnabledPerResponse(SdkHttpHeaders responseHeaders) { return responseHeaders.firstMatchingHeader(CHECKSUM_ENABLED_RESPONSE_HEADER) .filter(b -> b.equals(ENABLE_MD5_CHECKSUM_HEADER_VALUE)) .isPresent(); } /** * Check the {@link S3Configuration#checksumValidationEnabled()} to see if the checksum is enabled. * * @param executionAttributes the execution attributes * @return true if the trailing checksum is enabled in the config, false otherwise. */ private static boolean checksumEnabledPerConfig(ExecutionAttributes executionAttributes) { S3Configuration serviceConfiguration = (S3Configuration) executionAttributes.getAttribute(AwsSignerExecutionAttribute.SERVICE_CONFIG); return serviceConfiguration == null || serviceConfiguration.checksumValidationEnabled(); } }
4,613
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/checksums/ChecksumValidatingPublisher.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.checksums; import static java.lang.Math.toIntExact; import java.nio.ByteBuffer; import java.util.Arrays; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.core.checksums.SdkChecksum; import software.amazon.awssdk.core.exception.RetryableException; import software.amazon.awssdk.utils.BinaryUtils; @SdkInternalApi public final class ChecksumValidatingPublisher implements SdkPublisher<ByteBuffer> { private final Publisher<ByteBuffer> publisher; private final SdkChecksum sdkChecksum; private final long contentLength; public ChecksumValidatingPublisher(Publisher<ByteBuffer> publisher, SdkChecksum sdkChecksum, long contentLength) { this.publisher = publisher; this.sdkChecksum = sdkChecksum; this.contentLength = contentLength; } @Override public void subscribe(Subscriber<? super ByteBuffer> s) { if (contentLength > 0) { publisher.subscribe(new ChecksumValidatingSubscriber(s, sdkChecksum, contentLength)); } else { publisher.subscribe(new ChecksumSkippingSubscriber(s)); } } private static class ChecksumValidatingSubscriber implements Subscriber<ByteBuffer> { private static final int CHECKSUM_SIZE = 16; private final Subscriber<? super ByteBuffer> wrapped; private final SdkChecksum sdkChecksum; private final long strippedLength; private byte[] streamChecksum = new byte[CHECKSUM_SIZE]; private long lengthRead = 0; ChecksumValidatingSubscriber(Subscriber<? super ByteBuffer> wrapped, SdkChecksum sdkChecksum, long contentLength) { this.wrapped = wrapped; this.sdkChecksum = sdkChecksum; this.strippedLength = contentLength - CHECKSUM_SIZE; } @Override public void onSubscribe(Subscription s) { wrapped.onSubscribe(s); } @Override public void onNext(ByteBuffer byteBuffer) { byte[] buf = BinaryUtils.copyBytesFrom(byteBuffer); if (lengthRead < strippedLength) { int toUpdate = (int) Math.min(strippedLength - lengthRead, buf.length); sdkChecksum.update(buf, 0, toUpdate); } lengthRead += buf.length; if (lengthRead >= strippedLength) { // Incoming buffer contains at least a bit of the checksum // Code below covers both cases of the incoming buffer relative to checksum border // a) buffer starts before checksum border and extends into checksum // |<------ data ------->|<--cksum-->| <--- original data // |<---buffer--->| <--- incoming buffer // |<------->| <--- checksum bytes so far // |<-->| <--- bufChecksumOffset // | <--- streamChecksumOffset // b) buffer starts at or after checksum border // |<------ data ------->|<--cksum-->| <--- original data // |<-->| <--- incoming buffer // |<------>| <--- checksum bytes so far // | <--- bufChecksumOffset // |<->| <--- streamChecksumOffset int cksumBytesSoFar = toIntExact(lengthRead - strippedLength); int bufChecksumOffset = (buf.length > cksumBytesSoFar) ? (buf.length - cksumBytesSoFar) : 0; int streamChecksumOffset = (buf.length > cksumBytesSoFar) ? 0 : (cksumBytesSoFar - buf.length); int cksumBytes = Math.min(cksumBytesSoFar, buf.length); System.arraycopy(buf, bufChecksumOffset, streamChecksum, streamChecksumOffset, cksumBytes); if (buf.length > cksumBytesSoFar) { wrapped.onNext(ByteBuffer.wrap(Arrays.copyOfRange(buf, 0, buf.length - cksumBytesSoFar))); } else { // Always be sure to satisfy the wrapped publisher's demand. wrapped.onNext(ByteBuffer.allocate(0)); // TODO: The most efficient implementation would request more from the upstream publisher instead of relying // on the downstream publisher to do that, but that's much more complicated: it requires tracking // outstanding demand from the downstream publisher. Long-term we should migrate to an RxJava publisher // implementation to reduce how error-prone our publisher implementations are. } } else { // Incoming buffer totally excludes the checksum wrapped.onNext(byteBuffer); } } @Override public void onError(Throwable t) { wrapped.onError(t); } @Override public void onComplete() { if (strippedLength > 0) { byte[] computedChecksum = sdkChecksum.getChecksumBytes(); if (!Arrays.equals(computedChecksum, streamChecksum)) { onError(RetryableException.create( String.format("Data read has a different checksum than expected. Was 0x%s, but expected 0x%s. " + "Common causes: (1) You modified a request ByteBuffer before it could be " + "written to the service. Please ensure your data source does not modify the " + " byte buffers after you pass them to the SDK. (2) The data was corrupted between the " + "client and service. Note: Despite this error, the upload still completed and was " + "persisted in S3.", BinaryUtils.toHex(computedChecksum), BinaryUtils.toHex(streamChecksum)))); return; // Return after onError and not call onComplete below } } wrapped.onComplete(); } } private static class ChecksumSkippingSubscriber implements Subscriber<ByteBuffer> { private static final int CHECKSUM_SIZE = 16; private final Subscriber<? super ByteBuffer> wrapped; ChecksumSkippingSubscriber(Subscriber<? super ByteBuffer> wrapped) { this.wrapped = wrapped; } @Override public void onSubscribe(Subscription s) { wrapped.onSubscribe(s); } @Override public void onNext(ByteBuffer byteBuffer) { byte[] buf = BinaryUtils.copyBytesFrom(byteBuffer); wrapped.onNext(ByteBuffer.wrap(Arrays.copyOfRange(buf, 0, buf.length - CHECKSUM_SIZE))); } @Override public void onError(Throwable t) { wrapped.onError(t); } @Override public void onComplete() { wrapped.onComplete(); } } }
4,614
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/checksums/ChecksumCalculatingAsyncRequestBody.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.checksums; import java.nio.ByteBuffer; import java.util.Optional; import java.util.concurrent.atomic.AtomicLong; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.checksums.SdkChecksum; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.utils.BinaryUtils; @SdkInternalApi public class ChecksumCalculatingAsyncRequestBody implements AsyncRequestBody { private final Long contentLength; private final AsyncRequestBody wrapped; private final SdkChecksum sdkChecksum; public ChecksumCalculatingAsyncRequestBody(SdkHttpRequest request, AsyncRequestBody wrapped, SdkChecksum sdkChecksum) { this.contentLength = request.firstMatchingHeader("Content-Length") .map(Long::parseLong) .orElseGet(() -> wrapped.contentLength() .orElse(null)); this.wrapped = wrapped; this.sdkChecksum = sdkChecksum; } @Override public Optional<Long> contentLength() { return wrapped.contentLength(); } @Override public String contentType() { return wrapped.contentType(); } @Override public void subscribe(Subscriber<? super ByteBuffer> s) { sdkChecksum.reset(); wrapped.subscribe(new ChecksumCalculatingSubscriber(s, sdkChecksum, contentLength)); } private static final class ChecksumCalculatingSubscriber implements Subscriber<ByteBuffer> { private final AtomicLong contentRead = new AtomicLong(0); private final Subscriber<? super ByteBuffer> wrapped; private final SdkChecksum checksum; private final Long contentLength; ChecksumCalculatingSubscriber(Subscriber<? super ByteBuffer> wrapped, SdkChecksum sdkChecksum, Long contentLength) { this.wrapped = wrapped; this.checksum = sdkChecksum; this.contentLength = contentLength; } @Override public void onSubscribe(Subscription s) { wrapped.onSubscribe(s); } @Override public void onNext(ByteBuffer byteBuffer) { int amountToReadFromByteBuffer = getAmountToReadFromByteBuffer(byteBuffer); if (amountToReadFromByteBuffer > 0) { byte[] buf = BinaryUtils.copyBytesFrom(byteBuffer, amountToReadFromByteBuffer); checksum.update(buf, 0, amountToReadFromByteBuffer); } wrapped.onNext(byteBuffer); } private int getAmountToReadFromByteBuffer(ByteBuffer byteBuffer) { // If content length is null, we should include everything in the checksum because the stream is essentially // unbounded. if (contentLength == null) { return byteBuffer.remaining(); } long amountReadSoFar = contentRead.getAndAdd(byteBuffer.remaining()); long amountRemaining = Math.max(0, contentLength - amountReadSoFar); if (amountRemaining > byteBuffer.remaining()) { return byteBuffer.remaining(); } else { return Math.toIntExact(amountRemaining); } } @Override public void onError(Throwable t) { wrapped.onError(t); } @Override public void onComplete() { wrapped.onComplete(); } } }
4,615
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/checksums/ChecksumCalculatingInputStream.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.checksums; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.checksums.SdkChecksum; @SdkInternalApi public class ChecksumCalculatingInputStream extends FilterInputStream { private final SdkChecksum checkSum; private final InputStream inputStream; private boolean endOfStream = false; /** * Creates an input stream using the specified Checksum. * * @param in the input stream to read * @param cksum the Checksum implementation to use for computing the checksum */ public ChecksumCalculatingInputStream(final InputStream in, final SdkChecksum cksum) { super(in); inputStream = in; checkSum = cksum; } /** * Reads from the underlying stream. If the end of the stream is reached, the * running checksum will be appended a byte at a time (1 per read call). * * @return byte read, if eos has been reached, -1 will be returned. */ @Override public int read() throws IOException { int read = -1; if (!endOfStream) { read = inputStream.read(); if (read != -1) { checkSum.update(read); } if (read == -1) { endOfStream = true; } } return read; } /** * Reads up to len bytes at a time from the input stream, updates the checksum. If the end of the stream has been reached * the checksum will be appended to the last 4 bytes. * * @param buf buffer to write into * @param off offset in the buffer to write to * @param len maximum number of bytes to attempt to read. * @return number of bytes written into buf, otherwise -1 will be returned to indicate eos. */ @Override public int read(byte[] buf, int off, int len) throws IOException { if (buf == null) { throw new NullPointerException(); } int read = -1; if (!endOfStream) { read = inputStream.read(buf, off, len); if (read != -1) { checkSum.update(buf, off, read); } if (read == -1) { endOfStream = true; } } return read; } /** * Resets stream state, including the running checksum. */ @Override public synchronized void reset() throws IOException { inputStream.reset(); checkSum.reset(); endOfStream = false; } public byte[] getChecksumBytes() { return checkSum.getChecksumBytes(); } }
4,616
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/checksums/ChecksumValidatingInputStream.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.checksums; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.checksums.SdkChecksum; import software.amazon.awssdk.core.exception.RetryableException; import software.amazon.awssdk.http.Abortable; import software.amazon.awssdk.utils.BinaryUtils; @SdkInternalApi public class ChecksumValidatingInputStream extends InputStream implements Abortable { private static final int CHECKSUM_SIZE = 16; private final SdkChecksum checkSum; private final InputStream inputStream; private long strippedLength; private byte[] streamChecksum = new byte[CHECKSUM_SIZE]; private long lengthRead = 0; // Preserve the computed checksum because some InputStream readers (e.g., java.util.Properties) read more than once at the // end of the stream. private byte[] computedChecksum; /** * Creates an input stream using the specified Checksum, input stream, and length. * * @param in the input stream * @param cksum the Checksum implementation * @param streamLength the total length of the expected stream (including the extra 4 bytes on the end). */ public ChecksumValidatingInputStream(InputStream in, SdkChecksum cksum, long streamLength) { inputStream = in; checkSum = cksum; this.strippedLength = streamLength - CHECKSUM_SIZE; } /** * Reads one byte at a time from the input stream, updates the checksum. If the end of the stream has been reached * the checksum will be compared to the stream's checksum amd a SdkClientException will be thrown. * * @return byte read, if a read happened, otherwise -1 will be returned to indicate eos. */ @Override public int read() throws IOException { int read = inputStream.read(); if (read != -1 && lengthRead < strippedLength) { checkSum.update(read); } if (read != -1) { lengthRead++; } if (read != -1 && lengthRead == strippedLength) { int byteRead = -1; byteRead = inputStream.read(); while (byteRead != -1 && lengthRead < strippedLength + CHECKSUM_SIZE) { int index = Math.min((int) (lengthRead - strippedLength), CHECKSUM_SIZE - 1); streamChecksum[index] = (byte) byteRead; lengthRead++; byteRead = inputStream.read(); } } if (read == -1) { validateAndThrow(); } return read; } /** * Reads up to len bytes at a time from the input stream, updates the checksum. If the end of the stream has been reached * the checksum will be compared to the stream's checksum amd a SdkClientException will be thrown. * * @param buf buffer to write into * @param off offset in the buffer to write to * @param len maximum number of bytes to attempt to read. * @return number of bytes written into buf, otherwise -1 will be returned to indicate eos. */ @Override public int read(byte[] buf, int off, int len) throws IOException { if (buf == null) { throw new NullPointerException(); } int read = -1; if (lengthRead < strippedLength) { long maxRead = Math.min(Integer.MAX_VALUE, strippedLength - lengthRead); int maxIterRead = (int) Math.min(maxRead, len); read = inputStream.read(buf, off, maxIterRead); int toUpdate = (int) Math.min(strippedLength - lengthRead, read); if (toUpdate > 0) { checkSum.update(buf, off, toUpdate); } lengthRead += read >= 0 ? read : 0; } if (lengthRead >= strippedLength) { int byteRead = 0; while ((byteRead = inputStream.read()) != -1) { int index = Math.min((int) (lengthRead - strippedLength), CHECKSUM_SIZE - 1); streamChecksum[index] = (byte) byteRead; lengthRead++; } if (read == -1) { validateAndThrow(); } } return read; } /** * Resets stream state, including the running checksum. */ @Override public synchronized void reset() throws IOException { inputStream.reset(); checkSum.reset(); lengthRead = 0; for (int i = 0; i < CHECKSUM_SIZE; i++) { streamChecksum[i] = 0; } } @Override public void abort() { if (inputStream instanceof Abortable) { ((Abortable) inputStream).abort(); } } @Override public void close() throws IOException { inputStream.close(); } private void validateAndThrow() { if (computedChecksum == null) { computedChecksum = checkSum.getChecksumBytes(); } if (!Arrays.equals(computedChecksum, streamChecksum)) { throw RetryableException.create( String.format("Data read has a different checksum than expected. Was 0x%s, but expected 0x%s. " + "This commonly means that the data was corrupted between the client and " + "service.", BinaryUtils.toHex(computedChecksum), BinaryUtils.toHex(streamChecksum))); } } }
4,617
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/checksums/ChecksumConstant.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.checksums; import software.amazon.awssdk.annotations.SdkInternalApi; @SdkInternalApi public final class ChecksumConstant { /** * Header name for the content-length of an S3 object. */ public static final String CONTENT_LENGTH_HEADER = "Content-Length"; /** * Header name for specifying S3 to send a trailing checksum. */ public static final String ENABLE_CHECKSUM_REQUEST_HEADER = "x-amz-te"; /** * Header name for specifying if trailing checksums were sent on an object. */ public static final String CHECKSUM_ENABLED_RESPONSE_HEADER = "x-amz-transfer-encoding"; /** * Header value for specifying MD5 as the trailing checksum of an object. */ public static final String ENABLE_MD5_CHECKSUM_HEADER_VALUE = "append-md5"; /** * Header value for specifying server side encryption. */ public static final String SERVER_SIDE_ENCRYPTION_HEADER = "x-amz-server-side-encryption"; /** * Header value for specifying server side encryption with a customer managed key. */ public static final String SERVER_SIDE_CUSTOMER_ENCRYPTION_HEADER = "x-amz-server-side-encryption-customer-algorithm"; /** * Length of an MD5 checksum in bytes. */ public static final int S3_MD5_CHECKSUM_LENGTH = 16; private ChecksumConstant() { } }
4,618
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/multipart/MultipartConfiguration.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.multipart; import java.util.function.Consumer; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.S3AsyncClientBuilder; import software.amazon.awssdk.services.s3.model.CopyObjectRequest; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * Class that hold configuration properties related to multipart operation for a {@link S3AsyncClient}. Passing this class to the * {@link S3AsyncClientBuilder#multipartConfiguration(MultipartConfiguration)} will enable automatic conversion of * {@link S3AsyncClient#putObject(Consumer, AsyncRequestBody)}, {@link S3AsyncClient#copyObject(CopyObjectRequest)} to their * respective multipart operation. * <p> * <em>Note</em>: The multipart operation for {@link S3AsyncClient#getObject(GetObjectRequest, AsyncResponseTransformer)} is * temporarily disabled and will result in throwing a {@link UnsupportedOperationException} if called when configured for * multipart operation. */ @SdkPublicApi public final class MultipartConfiguration implements ToCopyableBuilder<MultipartConfiguration.Builder, MultipartConfiguration> { private final Long thresholdInBytes; private final Long minimumPartSizeInBytes; private final Long apiCallBufferSizeInBytes; private MultipartConfiguration(DefaultMultipartConfigBuilder builder) { this.thresholdInBytes = builder.thresholdInBytes; this.minimumPartSizeInBytes = builder.minimumPartSizeInBytes; this.apiCallBufferSizeInBytes = builder.apiCallBufferSizeInBytes; } public static Builder builder() { return new DefaultMultipartConfigBuilder(); } @Override public Builder toBuilder() { return builder() .apiCallBufferSizeInBytes(apiCallBufferSizeInBytes) .minimumPartSizeInBytes(minimumPartSizeInBytes) .thresholdInBytes(thresholdInBytes); } /** * Indicates the value of the configured threshold, in bytes. Any request whose size is less than the configured value will * not use multipart operation * @return the value of the configured threshold. */ public Long thresholdInBytes() { return this.thresholdInBytes; } /** * Indicated the size, in bytes, of each individual part of the part requests. The actual part size used might be bigger to * conforms to the maximum number of parts allowed per multipart requests. * @return the value of the configured part size. */ public Long minimumPartSizeInBytes() { return this.minimumPartSizeInBytes; } /** * The maximum memory, in bytes, that the SDK will use to buffer requests content into memory. * @return the value of the configured maximum memory usage. */ public Long apiCallBufferSizeInBytes() { return this.apiCallBufferSizeInBytes; } /** * Builder for a {@link MultipartConfiguration}. */ public interface Builder extends CopyableBuilder<Builder, MultipartConfiguration> { /** * Configure the size threshold, in bytes, for when to use multipart upload. Uploads/copies over this size will * automatically use a multipart upload strategy, while uploads/copies smaller than this threshold will use a single * connection to upload/copy the whole object. * * <p> * Multipart uploads are easier to recover from and also potentially faster than single part uploads, especially when the * upload parts can be uploaded in parallel. Because there are additional network API calls, small objects are still * recommended to use a single connection for the upload. See * <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/mpuoverview.html">Uploading and copying objects using * multipart upload</a>. * * <p> * By default, it is the same as {@link #minimumPartSizeInBytes(Long)}. * * @param thresholdInBytes the value of the threshold to set. * @return an instance of this builder. */ Builder thresholdInBytes(Long thresholdInBytes); /** * Indicates the value of the configured threshold. * @return the value of the threshold. */ Long thresholdInBytes(); /** * Configures the part size, in bytes, to be used in each individual part requests. * Only used for putObject and copyObject operations. * <p> * When uploading large payload, the size of the payload of each individual part requests might actually be * bigger than * the configured value since there is a limit to the maximum number of parts possible per multipart request. If the * configured part size would lead to a number of parts higher than the maximum allowed, a larger part size will be * calculated instead to allow fewer part to be uploaded, to avoid the limit imposed on the maximum number of parts. * <p> * In the case where the {@code minimumPartSizeInBytes} is set to a value higher than the {@code thresholdInBytes}, when * the client receive a request with a size smaller than a single part multipart operation will <em>NOT</em> be performed * even if the size of the request is larger than the threshold. * <p> * Default value: 8 Mib * * @param minimumPartSizeInBytes the value of the part size to set * @return an instance of this builder. */ Builder minimumPartSizeInBytes(Long minimumPartSizeInBytes); /** * Indicated the value of the part configured size. * @return the value of the part size */ Long minimumPartSizeInBytes(); /** * Configures the maximum amount of memory, in bytes, the SDK will use to buffer content of requests in memory. * Increasing this value may lead to better performance at the cost of using more memory. * <p> * Default value: If not specified, the SDK will use the equivalent of four parts worth of memory, so 32 Mib by default. * * @param apiCallBufferSizeInBytes the value of the maximum memory usage. * @return an instance of this builder. */ Builder apiCallBufferSizeInBytes(Long apiCallBufferSizeInBytes); /** * Indicates the value of the maximum memory usage that the SDK will use. * @return the value of the maximum memory usage. */ Long apiCallBufferSizeInBytes(); } private static class DefaultMultipartConfigBuilder implements Builder { private Long thresholdInBytes; private Long minimumPartSizeInBytes; private Long apiCallBufferSizeInBytes; public Builder thresholdInBytes(Long thresholdInBytes) { this.thresholdInBytes = thresholdInBytes; return this; } public Long thresholdInBytes() { return this.thresholdInBytes; } public Builder minimumPartSizeInBytes(Long minimumPartSizeInBytes) { this.minimumPartSizeInBytes = minimumPartSizeInBytes; return this; } public Long minimumPartSizeInBytes() { return this.minimumPartSizeInBytes; } @Override public Builder apiCallBufferSizeInBytes(Long maximumMemoryUsageInBytes) { this.apiCallBufferSizeInBytes = maximumMemoryUsageInBytes; return this; } @Override public Long apiCallBufferSizeInBytes() { return apiCallBufferSizeInBytes; } @Override public MultipartConfiguration build() { return new MultipartConfiguration(this); } } }
4,619
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner/S3Presigner.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.presigner; import java.net.URI; import java.net.URLConnection; import java.util.function.Consumer; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.awscore.presigner.PresignedRequest; import software.amazon.awssdk.awscore.presigner.SdkPresigner; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.providers.DefaultAwsRegionProviderChain; import software.amazon.awssdk.services.s3.S3Configuration; import software.amazon.awssdk.services.s3.internal.signing.DefaultS3Presigner; import software.amazon.awssdk.services.s3.model.AbortMultipartUploadRequest; import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadRequest; import software.amazon.awssdk.services.s3.model.CreateMultipartUploadRequest; import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.model.UploadPartRequest; import software.amazon.awssdk.services.s3.presigner.model.AbortMultipartUploadPresignRequest; import software.amazon.awssdk.services.s3.presigner.model.CompleteMultipartUploadPresignRequest; import software.amazon.awssdk.services.s3.presigner.model.CreateMultipartUploadPresignRequest; import software.amazon.awssdk.services.s3.presigner.model.DeleteObjectPresignRequest; import software.amazon.awssdk.services.s3.presigner.model.GetObjectPresignRequest; import software.amazon.awssdk.services.s3.presigner.model.PresignedAbortMultipartUploadRequest; import software.amazon.awssdk.services.s3.presigner.model.PresignedCompleteMultipartUploadRequest; import software.amazon.awssdk.services.s3.presigner.model.PresignedCreateMultipartUploadRequest; import software.amazon.awssdk.services.s3.presigner.model.PresignedDeleteObjectRequest; import software.amazon.awssdk.services.s3.presigner.model.PresignedGetObjectRequest; import software.amazon.awssdk.services.s3.presigner.model.PresignedPutObjectRequest; import software.amazon.awssdk.services.s3.presigner.model.PresignedUploadPartRequest; import software.amazon.awssdk.services.s3.presigner.model.PutObjectPresignRequest; import software.amazon.awssdk.services.s3.presigner.model.UploadPartPresignRequest; /** * Enables signing an S3 {@link SdkRequest} so that it can be executed without requiring any additional authentication on the * part of the caller. * <p/> * * For example: if Alice has access to an S3 object, and she wants to temporarily share access to that object with Bob, she * can generate a pre-signed {@link GetObjectRequest} to secure share with Bob so that he can download the object without * requiring access to Alice's credentials. * <p/> * * <h2>Signature Duration</h2> * <p/> * * Pre-signed requests are only valid for a finite period of time, referred to as the signature duration. This signature * duration is configured when the request is generated, and cannot be longer than 7 days. Attempting to generate a signature * longer than 7 days in the future will fail at generation time. Attempting to use a pre-signed request after the signature * duration has passed will result in an access denied response from the service. * <p/> * * <h3>Example Usage</h3> * <p/> * * <pre> * {@code * // Create an S3Presigner using the default region and credentials. * // This is usually done at application startup, because creating a presigner can be expensive. * S3Presigner presigner = S3Presigner.create(); * * // Create a GetObjectRequest to be pre-signed * GetObjectRequest getObjectRequest = * GetObjectRequest.builder() * .bucket("my-bucket") * .key("my-key") * .build(); * * // Create a GetObjectPresignRequest to specify the signature duration * GetObjectPresignRequest getObjectPresignRequest = * GetObjectPresignRequest.builder() * .signatureDuration(Duration.ofMinutes(10)) * .getObjectRequest(getObjectRequest) * .build(); * * // Generate the presigned request * PresignedGetObjectRequest presignedGetObjectRequest = * presigner.presignGetObject(getObjectPresignRequest); * * // Log the presigned URL, for example. * System.out.println("Presigned URL: " + presignedGetObjectRequest.url()); * * // It is recommended to close the S3Presigner when it is done being used, because some credential * // providers (e.g. if your AWS profile is configured to assume an STS role) require system resources * // that need to be freed. If you are using one S3Presigner per application (as recommended), this * // usually is not needed. * presigner.close(); * } * </pre> * <p/> * * <h2>Browser Compatibility</h2> * <p/> * * Some pre-signed requests can be executed by a web browser. These "browser compatible" pre-signed requests * do not require the customer to send anything other than a "host" header when performing an HTTP GET against * the pre-signed URL. * <p/> * * Whether a pre-signed request is "browser compatible" can be determined by checking the * {@link PresignedRequest#isBrowserExecutable()} flag. It is recommended to always check this flag when the pre-signed * request needs to be executed by a browser, because some request fields will result in the pre-signed request not * being browser-compatible. * <p /> * * <h3>Configurations that affect browser compatibility</h3> * <h4>Enabling Checking Validation</h4> * If checksum validations are enabled, the presigned URL will no longer be browser compatible because it adds a signed header * that must be included in the HTTP request. * * Checksum validation is disabled in the presigner by default, but when using a custom {@link S3Configuration} when enabling * features like path style access or accelerate mode, it must be explicitly disabled: * * <pre> * S3Presigner presigner = S3Presigner.builder() * .serviceConfiguration(S3Configuration.builder() * .checksumValidationEnabled(false) * .build()) * .build(); * </pre> * * * <h2>Executing a Pre-Signed Request from Java code</h2> * <p /> * * Browser-compatible requests (see above) can be executed using a web browser. All pre-signed requests can be executed * from Java code. This documentation describes two methods for executing a pre-signed request: (1) using the JDK's * {@link URLConnection} class, (2) using an SDK synchronous {@link SdkHttpClient} class. * * <p /> * <i>Using {code URLConnection}:</i> * * <p /> * <pre> * // Create a pre-signed request using one of the "presign" methods on S3Presigner * PresignedRequest presignedRequest = ...; * * // Create a JDK HttpURLConnection for communicating with S3 * HttpURLConnection connection = (HttpURLConnection) presignedRequest.url().openConnection(); * * // Specify any headers that are needed by the service (not needed when isBrowserExecutable is true) * presignedRequest.httpRequest().headers().forEach((header, values) -> { * values.forEach(value -> { * connection.addRequestProperty(header, value); * }); * }); * * // Send any request payload that is needed by the service (not needed when isBrowserExecutable is true) * if (presignedRequest.signedPayload().isPresent()) { * connection.setDoOutput(true); * try (InputStream signedPayload = presignedRequest.signedPayload().get().asInputStream(); * OutputStream httpOutputStream = connection.getOutputStream()) { * IoUtils.copy(signedPayload, httpOutputStream); * } * } * * // Download the result of executing the request * try (InputStream content = connection.getInputStream()) { * System.out.println("Service returned response: "); * IoUtils.copy(content, System.out); * } * </pre> * <p /> * * <i>Using {code SdkHttpClient}:</i> * <p /> * * <pre> * // Create a pre-signed request using one of the "presign" methods on S3Presigner * PresignedRequest presignedRequest = ...; * * // Create an SdkHttpClient using one of the implementations provided by the SDK * SdkHttpClient httpClient = ApacheHttpClient.builder().build(); // or UrlConnectionHttpClient.create() * * // Specify any request payload that is needed by the service (not needed when isBrowserExecutable is true) * ContentStreamProvider requestPayload = * presignedRequest.signedPayload() * .map(SdkBytes::asContentStreamProvider) * .orElse(null); * * // Create the request for sending to the service * HttpExecuteRequest request = * HttpExecuteRequest.builder() * .request(presignedRequest.httpRequest()) * .contentStreamProvider(requestPayload) * .build(); * * // Call the service * HttpExecuteResponse response = httpClient.prepareRequest(request).call(); * * // Download the result of executing the request * if (response.responseBody().isPresent()) { * try (InputStream responseStream = response.responseBody().get()) { * System.out.println("Service returned response: "); * IoUtils.copy(content, System.out); * } * } * </pre> */ @SdkPublicApi @Immutable @ThreadSafe public interface S3Presigner extends SdkPresigner { /** * Create an {@link S3Presigner} with default configuration. The region will be loaded from the * {@link DefaultAwsRegionProviderChain} and credentials will be loaded from the {@link DefaultCredentialsProvider}. * <p/> * This is usually done at application startup, because creating a presigner can be expensive. It is recommended to * {@link #close()} the {@code S3Presigner} when it is done being used. */ static S3Presigner create() { return builder().build(); } /** * Create an {@link S3Presigner.Builder} that can be used to configure and create a {@link S3Presigner}. * <p/> * This is usually done at application startup, because creating a presigner can be expensive. It is recommended to * {@link #close()} the {@code S3Presigner} when it is done being used. */ static Builder builder() { return DefaultS3Presigner.builder(); } /** * Presign a {@link GetObjectRequest} so that it can be executed at a later time without requiring additional * signing or authentication. * <p/> * * <b>Example Usage</b> * <p/> * * <pre> * {@code * S3Presigner presigner = ...; * * // Create a GetObjectRequest to be pre-signed * GetObjectRequest getObjectRequest = ...; * * // Create a GetObjectPresignRequest to specify the signature duration * GetObjectPresignRequest getObjectPresignRequest = * GetObjectPresignRequest.builder() * .signatureDuration(Duration.ofMinutes(10)) * .getObjectRequest(request) * .build(); * * // Generate the presigned request * PresignedGetObjectRequest presignedGetObjectRequest = * presigner.presignGetObject(getObjectPresignRequest); * * if (presignedGetObjectRequest.isBrowserExecutable()) * System.out.println("The pre-signed request can be executed using a web browser by " + * "visiting the following URL: " + presignedGetObjectRequest.url()); * else * System.out.println("The pre-signed request has an HTTP method, headers or a payload " + * "that prohibits it from being executed by a web browser. See the S3Presigner " + * "class-level documentation for an example of how to execute this pre-signed " + * "request from Java code."); * } * </pre> */ PresignedGetObjectRequest presignGetObject(GetObjectPresignRequest request); /** * Presign a {@link GetObjectRequest} so that it can be executed at a later time without requiring additional * signing or authentication. * <p /> * This is a shorter method of invoking {@link #presignGetObject(GetObjectPresignRequest)} without needing * to call {@code GetObjectPresignRequest.builder()} or {@code .build()}. * * @see #presignGetObject(GetObjectPresignRequest) */ default PresignedGetObjectRequest presignGetObject(Consumer<GetObjectPresignRequest.Builder> request) { GetObjectPresignRequest.Builder builder = GetObjectPresignRequest.builder(); request.accept(builder); return presignGetObject(builder.build()); } /** * Presign a {@link PutObjectRequest} so that it can be executed at a later time without requiring additional * signing or authentication. * <p> * <b>Example Usage</b> * * <pre> * {@code * S3Presigner presigner = ...; * * // Create a PutObjectRequest to be pre-signed * PutObjectRequest putObjectRequest = ...; * * // Create a PutObjectPresignRequest to specify the signature duration * PutObjectPresignRequest putObjectPresignRequest = * PutObjectPresignRequest.builder() * .signatureDuration(Duration.ofMinutes(10)) * .putObjectRequest(request) * .build(); * * // Generate the presigned request * PresignedPutObjectRequest presignedPutObjectRequest = * presigner.presignPutObject(putObjectPresignRequest); * } * </pre> */ PresignedPutObjectRequest presignPutObject(PutObjectPresignRequest request); /** * Presign a {@link PutObjectRequest} so that it can be executed at a later time without requiring additional * signing or authentication. * <p> * This is a shorter method of invoking {@link #presignPutObject(PutObjectPresignRequest)} without needing * to call {@code PutObjectPresignRequest.builder()} or {@code .build()}. * * @see #presignPutObject(PutObjectPresignRequest) */ default PresignedPutObjectRequest presignPutObject(Consumer<PutObjectPresignRequest.Builder> request) { PutObjectPresignRequest.Builder builder = PutObjectPresignRequest.builder(); request.accept(builder); return presignPutObject(builder.build()); } /** * Presign a {@link DeleteObjectRequest} so that it can be executed at a later time without requiring additional * signing or authentication. * <p> * <b>Example Usage</b> * * <pre> * {@code * S3Presigner presigner = ...; * * // Create a DeleteObjectRequest to be pre-signed * DeleteObjectRequest deleteObjectRequest = ...; * * // Create a PutObjectPresignRequest to specify the signature duration * DeleteObjectPresignRequest deleteObjectPresignRequest = * DeleteObjectPresignRequest.builder() * .signatureDuration(Duration.ofMinutes(10)) * .deleteObjectRequest(deleteObjectRequest) * .build(); * * // Generate the presigned request * PresignedDeleteObjectRequest presignedDeleteObjectRequest = * presigner.presignDeleteObject(deleteObjectPresignRequest); * } * </pre> */ PresignedDeleteObjectRequest presignDeleteObject(DeleteObjectPresignRequest request); /** * Presign a {@link DeleteObjectRequest} so that it can be executed at a later time without requiring additional * signing or authentication. * <p> * This is a shorter method of invoking {@link #presignDeleteObject(DeleteObjectPresignRequest)} without needing * to call {@code DeleteObjectPresignRequest.builder()} or {@code .build()}. * * @see #presignDeleteObject(PresignedDeleteObjectRequest) */ default PresignedDeleteObjectRequest presignDeleteObject(Consumer<DeleteObjectPresignRequest.Builder> request) { DeleteObjectPresignRequest.Builder builder = DeleteObjectPresignRequest.builder(); request.accept(builder); return presignDeleteObject(builder.build()); } /** * Presign a {@link CreateMultipartUploadRequest} so that it can be executed at a later time without requiring additional * signing or authentication. * <p> * <b>Example Usage</b> * * <pre> * {@code * S3Presigner presigner = ...; * * // Create a CreateMultipartUploadRequest to be pre-signed * CreateMultipartUploadRequest createMultipartUploadRequest = ...; * * // Create a CreateMultipartUploadPresignRequest to specify the signature duration * CreateMultipartUploadPresignRequest createMultipartUploadPresignRequest = * CreateMultipartUploadPresignRequest.builder() * .signatureDuration(Duration.ofMinutes(10)) * .createMultipartUploadRequest(request) * .build(); * * // Generate the presigned request * PresignedCreateMultipartUploadRequest presignedCreateMultipartUploadRequest = * presigner.presignCreateMultipartUpload(createMultipartUploadPresignRequest); * } * </pre> */ PresignedCreateMultipartUploadRequest presignCreateMultipartUpload(CreateMultipartUploadPresignRequest request); /** * Presign a {@link CreateMultipartUploadRequest} so that it can be executed at a later time without requiring additional * signing or authentication. * <p> * This is a shorter method of invoking {@link #presignCreateMultipartUpload(CreateMultipartUploadPresignRequest)} without * needing to call {@code CreateMultipartUploadPresignRequest.builder()} or {@code .build()}. * * @see #presignCreateMultipartUpload(CreateMultipartUploadPresignRequest) */ default PresignedCreateMultipartUploadRequest presignCreateMultipartUpload( Consumer<CreateMultipartUploadPresignRequest.Builder> request) { CreateMultipartUploadPresignRequest.Builder builder = CreateMultipartUploadPresignRequest.builder(); request.accept(builder); return presignCreateMultipartUpload(builder.build()); } /** * Presign a {@link UploadPartRequest} so that it can be executed at a later time without requiring additional * signing or authentication. * <p> * * <b>Example Usage</b> * * <pre> * {@code * S3Presigner presigner = ...; * * // Create a UploadPartRequest to be pre-signed * UploadPartRequest uploadPartRequest = ...; * * // Create a UploadPartPresignRequest to specify the signature duration * UploadPartPresignRequest uploadPartPresignRequest = * UploadPartPresignRequest.builder() * .signatureDuration(Duration.ofMinutes(10)) * .uploadPartRequest(request) * .build(); * * // Generate the presigned request * PresignedUploadPartRequest presignedUploadPartRequest = * presigner.presignUploadPart(uploadPartPresignRequest); * } * </pre> */ PresignedUploadPartRequest presignUploadPart(UploadPartPresignRequest request); /** * Presign a {@link UploadPartRequest} so that it can be executed at a later time without requiring additional * signing or authentication. * <p> * This is a shorter method of invoking {@link #presignUploadPart(UploadPartPresignRequest)} without needing * to call {@code UploadPartPresignRequest.builder()} or {@code .build()}. * * @see #presignUploadPart(UploadPartPresignRequest) */ default PresignedUploadPartRequest presignUploadPart(Consumer<UploadPartPresignRequest.Builder> request) { UploadPartPresignRequest.Builder builder = UploadPartPresignRequest.builder(); request.accept(builder); return presignUploadPart(builder.build()); } /** * Presign a {@link CompleteMultipartUploadRequest} so that it can be executed at a later time without requiring additional * signing or authentication. * <p> * * <b>Example Usage</b> * * <pre> * {@code * S3Presigner presigner = ...; * * // Complete a CompleteMultipartUploadRequest to be pre-signed * CompleteMultipartUploadRequest completeMultipartUploadRequest = ...; * * // Create a CompleteMultipartUploadPresignRequest to specify the signature duration * CompleteMultipartUploadPresignRequest completeMultipartUploadPresignRequest = * CompleteMultipartUploadPresignRequest.builder() * .signatureDuration(Duration.ofMinutes(10)) * .completeMultipartUploadRequest(request) * .build(); * * // Generate the presigned request * PresignedCompleteMultipartUploadRequest presignedCompleteMultipartUploadRequest = * presigner.presignCompleteMultipartUpload(completeMultipartUploadPresignRequest); * } * </pre> */ PresignedCompleteMultipartUploadRequest presignCompleteMultipartUpload(CompleteMultipartUploadPresignRequest request); /** * Presign a {@link CompleteMultipartUploadRequest} so that it can be executed at a later time without requiring additional * signing or authentication. * <p> * This is a shorter method of invoking {@link #presignCompleteMultipartUpload(CompleteMultipartUploadPresignRequest)} without * needing to call {@code CompleteMultipartUploadPresignRequest.builder()} or {@code .build()}. * * @see #presignCompleteMultipartUpload(CompleteMultipartUploadPresignRequest) */ default PresignedCompleteMultipartUploadRequest presignCompleteMultipartUpload( Consumer<CompleteMultipartUploadPresignRequest.Builder> request) { CompleteMultipartUploadPresignRequest.Builder builder = CompleteMultipartUploadPresignRequest.builder(); request.accept(builder); return presignCompleteMultipartUpload(builder.build()); } /** * Presign a {@link AbortMultipartUploadRequest} so that it can be executed at a later time without requiring additional * signing or authentication. * <p> * * <b>Example Usage</b> * * <pre> * {@code * S3Presigner presigner = ...; * * // Complete a AbortMultipartUploadRequest to be pre-signed * AbortMultipartUploadRequest abortMultipartUploadRequest = ...; * * // Create a AbortMultipartUploadPresignRequest to specify the signature duration * AbortMultipartUploadPresignRequest abortMultipartUploadPresignRequest = * AbortMultipartUploadPresignRequest.builder() * .signatureDuration(Duration.ofMinutes(10)) * .abortMultipartUploadRequest(request) * .build(); * * // Generate the presigned request * PresignedAbortMultipartUploadRequest presignedAbortMultipartUploadRequest = * presigner.presignAbortMultipartUpload(abortMultipartUploadPresignRequest); * } * </pre> */ PresignedAbortMultipartUploadRequest presignAbortMultipartUpload(AbortMultipartUploadPresignRequest request); /** * Presign a {@link AbortMultipartUploadRequest} so that it can be executed at a later time without requiring additional * signing or authentication. * <p> * This is a shorter method of invoking {@link #presignAbortMultipartUpload(AbortMultipartUploadPresignRequest)} without * needing to call {@code AbortMultipartUploadPresignRequest.builder()} or {@code .build()}. * * @see #presignAbortMultipartUpload(AbortMultipartUploadPresignRequest) */ default PresignedAbortMultipartUploadRequest presignAbortMultipartUpload( Consumer<AbortMultipartUploadPresignRequest.Builder> request) { AbortMultipartUploadPresignRequest.Builder builder = AbortMultipartUploadPresignRequest.builder(); request.accept(builder); return presignAbortMultipartUpload(builder.build()); } /** * A builder for creating {@link S3Presigner}s. Created using {@link #builder()}. */ @SdkPublicApi @NotThreadSafe interface Builder extends SdkPresigner.Builder { /** * Allows providing a custom S3 serviceConfiguration by providing a {@link S3Configuration} object; * * Note: chunkedEncodingEnabled and checksumValidationEnabled do not apply to presigned requests. * * @param serviceConfiguration {@link S3Configuration} * @return this Builder */ Builder serviceConfiguration(S3Configuration serviceConfiguration); @Override Builder region(Region region); @Override default Builder credentialsProvider(AwsCredentialsProvider credentialsProvider) { return credentialsProvider((IdentityProvider<? extends AwsCredentialsIdentity>) credentialsProvider); } @Override Builder credentialsProvider(IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider); @Override Builder dualstackEnabled(Boolean dualstackEnabled); @Override Builder fipsEnabled(Boolean dualstackEnabled); @Override Builder endpointOverride(URI endpointOverride); @Override S3Presigner build(); } }
4,620
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner/model/GetObjectPresignRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.presigner.model; import java.time.Duration; import java.util.function.Consumer; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.awscore.presigner.PresignRequest; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.s3.presigner.S3Presigner; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * A request to pre-sign a {@link GetObjectRequest} so that it can be executed at a later time without requiring additional * signing or authentication. * * @see S3Presigner#presignGetObject(GetObjectPresignRequest) * @see #builder() */ @SdkPublicApi @Immutable @ThreadSafe public final class GetObjectPresignRequest extends PresignRequest implements ToCopyableBuilder<GetObjectPresignRequest.Builder, GetObjectPresignRequest> { private final GetObjectRequest getObjectRequest; private GetObjectPresignRequest(DefaultBuilder builder) { super(builder); this.getObjectRequest = Validate.notNull(builder.getObjectRequest, "getObjectRequest"); } /** * Create a builder that can be used to create a {@link GetObjectPresignRequest}. * * @see S3Presigner#presignGetObject(GetObjectPresignRequest) */ public static Builder builder() { return new DefaultBuilder(); } /** * Retrieve the {@link GetObjectRequest} that should be presigned. */ public GetObjectRequest getObjectRequest() { return getObjectRequest; } @Override public Builder toBuilder() { return new DefaultBuilder(this); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } GetObjectPresignRequest that = (GetObjectPresignRequest) o; return getObjectRequest.equals(that.getObjectRequest); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + getObjectRequest.hashCode(); return result; } /** * A builder for a {@link GetObjectPresignRequest}, created with {@link #builder()}. */ @SdkPublicApi @NotThreadSafe public interface Builder extends PresignRequest.Builder, CopyableBuilder<GetObjectPresignRequest.Builder, GetObjectPresignRequest> { /** * Configure the {@link GetObjectRequest} that should be presigned. */ Builder getObjectRequest(GetObjectRequest getObjectRequest); /** * Configure the {@link GetObjectRequest} that should be presigned. * <p/> * This is a convenience method for invoking {@link #getObjectRequest(GetObjectRequest)} without needing to invoke * {@code GetObjectRequest.builder()} or {@code build()}. */ default Builder getObjectRequest(Consumer<GetObjectRequest.Builder> getObjectRequest) { GetObjectRequest.Builder builder = GetObjectRequest.builder(); getObjectRequest.accept(builder); return getObjectRequest(builder.build()); } @Override Builder signatureDuration(Duration signatureDuration); @Override GetObjectPresignRequest build(); } @SdkInternalApi private static final class DefaultBuilder extends PresignRequest.DefaultBuilder<DefaultBuilder> implements Builder { private GetObjectRequest getObjectRequest; private DefaultBuilder() { } private DefaultBuilder(GetObjectPresignRequest request) { super(request); this.getObjectRequest = request.getObjectRequest; } @Override public Builder getObjectRequest(GetObjectRequest getObjectRequest) { this.getObjectRequest = getObjectRequest; return this; } @Override public GetObjectPresignRequest build() { return new GetObjectPresignRequest(this); } } }
4,621
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner/model/PresignedUploadPartRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.presigner.model; import java.time.Instant; import java.util.List; import java.util.Map; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.awscore.presigner.PresignedRequest; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.services.s3.model.UploadPartRequest; import software.amazon.awssdk.services.s3.presigner.S3Presigner; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * A pre-signed {@link UploadPartRequest} that can be executed at a later time without requiring additional signing or * authentication. * * @see S3Presigner#presignUploadPart(UploadPartPresignRequest) * @see #builder() */ @SdkPublicApi @Immutable @ThreadSafe public class PresignedUploadPartRequest extends PresignedRequest implements ToCopyableBuilder<PresignedUploadPartRequest.Builder, PresignedUploadPartRequest> { private PresignedUploadPartRequest(DefaultBuilder builder) { super(builder); } /** * Create a builder that can be used to create a {@link PresignedUploadPartRequest}. * * @see S3Presigner#presignUploadPart(UploadPartPresignRequest) */ public static Builder builder() { return new DefaultBuilder(); } @Override public Builder toBuilder() { return new DefaultBuilder(this); } /** * A builder for a {@link PresignedUploadPartRequest}, created with {@link #builder()}. */ @SdkPublicApi @NotThreadSafe public interface Builder extends PresignedRequest.Builder, CopyableBuilder<PresignedUploadPartRequest.Builder, PresignedUploadPartRequest> { @Override Builder expiration(Instant expiration); @Override Builder isBrowserExecutable(Boolean isBrowserExecutable); @Override Builder signedHeaders(Map<String, List<String>> signedHeaders); @Override Builder signedPayload(SdkBytes signedPayload); @Override Builder httpRequest(SdkHttpRequest httpRequest); @Override PresignedUploadPartRequest build(); } @SdkInternalApi private static final class DefaultBuilder extends PresignedRequest.DefaultBuilder<DefaultBuilder> implements Builder { private DefaultBuilder() { } private DefaultBuilder(PresignedUploadPartRequest request) { super(request); } @Override public PresignedUploadPartRequest build() { return new PresignedUploadPartRequest(this); } } }
4,622
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner/model/PresignedDeleteObjectRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.presigner.model; import java.time.Instant; import java.util.List; import java.util.Map; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.awscore.presigner.PresignedRequest; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; import software.amazon.awssdk.services.s3.presigner.S3Presigner; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * A pre-signed a {@link DeleteObjectRequest} that can be executed at a later time without requiring additional signing or * authentication. * * @see S3Presigner#presignDeleteObject(DeleteObjectPresignRequest) * @see #builder() */ @SdkPublicApi @Immutable @ThreadSafe public class PresignedDeleteObjectRequest extends PresignedRequest implements ToCopyableBuilder<PresignedDeleteObjectRequest.Builder, PresignedDeleteObjectRequest> { protected PresignedDeleteObjectRequest(DefaultBuilder builder) { super(builder); } @Override public Builder toBuilder() { return new DefaultBuilder(this); } /** * Create a builder that can be used to create a {@link PresignedDeleteObjectRequest}. * * @see S3Presigner#presignDeleteObject(DeleteObjectPresignRequest) */ public static Builder builder() { return new DefaultBuilder(); } /** * A builder for a {@link PresignedDeleteObjectRequest}, created with {@link #builder()}. */ @SdkPublicApi @NotThreadSafe public interface Builder extends PresignedRequest.Builder, CopyableBuilder<PresignedDeleteObjectRequest.Builder, PresignedDeleteObjectRequest> { @Override Builder expiration(Instant expiration); @Override Builder isBrowserExecutable(Boolean isBrowserExecutable); @Override Builder signedHeaders(Map<String, List<String>> signedHeaders); @Override Builder signedPayload(SdkBytes signedPayload); @Override Builder httpRequest(SdkHttpRequest httpRequest); @Override PresignedDeleteObjectRequest build(); } @SdkInternalApi private static final class DefaultBuilder extends PresignedRequest.DefaultBuilder<DefaultBuilder> implements PresignedDeleteObjectRequest.Builder { private DefaultBuilder() { } private DefaultBuilder(PresignedDeleteObjectRequest presignedDeleteObjectRequest) { super(presignedDeleteObjectRequest); } @Override public PresignedDeleteObjectRequest build() { return new PresignedDeleteObjectRequest(this); } } }
4,623
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner/model/PresignedCompleteMultipartUploadRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.presigner.model; import java.time.Instant; import java.util.List; import java.util.Map; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.awscore.presigner.PresignedRequest; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadRequest; import software.amazon.awssdk.services.s3.presigner.S3Presigner; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * A pre-signed {@link CompleteMultipartUploadRequest} that can be executed at a later time without requiring additional signing * or authentication. * * @see S3Presigner#presignCompleteMultipartUpload(CompleteMultipartUploadPresignRequest) * @see #builder() */ @SdkPublicApi @Immutable @ThreadSafe public class PresignedCompleteMultipartUploadRequest extends PresignedRequest implements ToCopyableBuilder<PresignedCompleteMultipartUploadRequest.Builder, PresignedCompleteMultipartUploadRequest> { private PresignedCompleteMultipartUploadRequest(DefaultBuilder builder) { super(builder); } /** * Create a builder that can be used to create a {@link PresignedCompleteMultipartUploadRequest}. * * @see S3Presigner#presignCompleteMultipartUpload(CompleteMultipartUploadPresignRequest) */ public static Builder builder() { return new DefaultBuilder(); } @Override public Builder toBuilder() { return new DefaultBuilder(this); } /** * A builder for a {@link PresignedCompleteMultipartUploadRequest}, created with {@link #builder()}. */ @SdkPublicApi @NotThreadSafe public interface Builder extends PresignedRequest.Builder, CopyableBuilder<PresignedCompleteMultipartUploadRequest.Builder, PresignedCompleteMultipartUploadRequest> { @Override Builder expiration(Instant expiration); @Override Builder isBrowserExecutable(Boolean isBrowserExecutable); @Override Builder signedHeaders(Map<String, List<String>> signedHeaders); @Override Builder signedPayload(SdkBytes signedPayload); @Override Builder httpRequest(SdkHttpRequest httpRequest); @Override PresignedCompleteMultipartUploadRequest build(); } @SdkInternalApi private static final class DefaultBuilder extends PresignedRequest.DefaultBuilder<DefaultBuilder> implements Builder { private DefaultBuilder() { } private DefaultBuilder(PresignedCompleteMultipartUploadRequest request) { super(request); } @Override public PresignedCompleteMultipartUploadRequest build() { return new PresignedCompleteMultipartUploadRequest(this); } } }
4,624
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner/model/UploadPartPresignRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.presigner.model; import java.time.Duration; import java.util.function.Consumer; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.awscore.presigner.PresignRequest; import software.amazon.awssdk.services.s3.model.UploadPartRequest; import software.amazon.awssdk.services.s3.presigner.S3Presigner; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * A request to pre-sign a {@link UploadPartRequest} so that it can be executed at a later time without requiring additional * signing or authentication. * * @see S3Presigner#presignUploadPart(UploadPartPresignRequest) * @see #builder() */ @SdkPublicApi @Immutable @ThreadSafe public final class UploadPartPresignRequest extends PresignRequest implements ToCopyableBuilder<UploadPartPresignRequest.Builder, UploadPartPresignRequest> { private final UploadPartRequest uploadPartRequest; private UploadPartPresignRequest(DefaultBuilder builder) { super(builder); this.uploadPartRequest = Validate.notNull(builder.uploadPartRequest, "uploadPartRequest"); } /** * Create a builder that can be used to create a {@link UploadPartPresignRequest}. * * @see S3Presigner#presignUploadPart(UploadPartPresignRequest) */ public static Builder builder() { return new DefaultBuilder(); } /** * Retrieve the {@link UploadPartRequest} that should be presigned. */ public UploadPartRequest uploadPartRequest() { return uploadPartRequest; } @Override public Builder toBuilder() { return new DefaultBuilder(this); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } UploadPartPresignRequest that = (UploadPartPresignRequest) o; return uploadPartRequest.equals(that.uploadPartRequest); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + uploadPartRequest.hashCode(); return result; } /** * A builder for a {@link UploadPartPresignRequest}, created with {@link #builder()}. */ @SdkPublicApi @NotThreadSafe public interface Builder extends PresignRequest.Builder, CopyableBuilder<UploadPartPresignRequest.Builder, UploadPartPresignRequest> { /** * Configure the {@link UploadPartRequest} that should be presigned. */ Builder uploadPartRequest(UploadPartRequest uploadPartRequest); /** * Configure the {@link UploadPartRequest} that should be presigned. * <p/> * This is a convenience method for invoking {@link #uploadPartRequest(UploadPartRequest)} without needing to invoke * {@code UploadPartRequest.builder()} or {@code build()}. */ default Builder uploadPartRequest(Consumer<UploadPartRequest.Builder> uploadPartRequest) { UploadPartRequest.Builder builder = UploadPartRequest.builder(); uploadPartRequest.accept(builder); return uploadPartRequest(builder.build()); } @Override Builder signatureDuration(Duration signatureDuration); @Override UploadPartPresignRequest build(); } @SdkInternalApi private static final class DefaultBuilder extends PresignRequest.DefaultBuilder<DefaultBuilder> implements Builder { private UploadPartRequest uploadPartRequest; private DefaultBuilder() { } private DefaultBuilder(UploadPartPresignRequest request) { super(request); this.uploadPartRequest = request.uploadPartRequest; } @Override public Builder uploadPartRequest(UploadPartRequest uploadPartRequest) { this.uploadPartRequest = uploadPartRequest; return this; } @Override public UploadPartPresignRequest build() { return new UploadPartPresignRequest(this); } } }
4,625
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner/model/PresignedPutObjectRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.presigner.model; import java.time.Instant; import java.util.List; import java.util.Map; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.awscore.presigner.PresignedRequest; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.presigner.S3Presigner; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * A pre-signed a {@link PutObjectRequest} that can be executed at a later time without requiring additional signing or * authentication. * * @see S3Presigner#presignPutObject(PutObjectPresignRequest) * @see #builder() */ @SdkPublicApi @Immutable @ThreadSafe public class PresignedPutObjectRequest extends PresignedRequest implements ToCopyableBuilder<PresignedPutObjectRequest.Builder, PresignedPutObjectRequest> { private PresignedPutObjectRequest(DefaultBuilder builder) { super(builder); } /** * Create a builder that can be used to create a {@link PresignedPutObjectRequest}. * * @see S3Presigner#presignPutObject(PutObjectPresignRequest) */ public static Builder builder() { return new DefaultBuilder(); } @Override public Builder toBuilder() { return new DefaultBuilder(this); } /** * A builder for a {@link PresignedPutObjectRequest}, created with {@link #builder()}. */ @SdkPublicApi @NotThreadSafe public interface Builder extends PresignedRequest.Builder, CopyableBuilder<PresignedPutObjectRequest.Builder, PresignedPutObjectRequest> { @Override Builder expiration(Instant expiration); @Override Builder isBrowserExecutable(Boolean isBrowserExecutable); @Override Builder signedHeaders(Map<String, List<String>> signedHeaders); @Override Builder signedPayload(SdkBytes signedPayload); @Override Builder httpRequest(SdkHttpRequest httpRequest); @Override PresignedPutObjectRequest build(); } @SdkInternalApi private static final class DefaultBuilder extends PresignedRequest.DefaultBuilder<DefaultBuilder> implements Builder { private DefaultBuilder() { } private DefaultBuilder(PresignedPutObjectRequest request) { super(request); } @Override public PresignedPutObjectRequest build() { return new PresignedPutObjectRequest(this); } } }
4,626
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner/model/PresignedCreateMultipartUploadRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.presigner.model; import java.time.Instant; import java.util.List; import java.util.Map; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.awscore.presigner.PresignedRequest; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.services.s3.model.CreateMultipartUploadRequest; import software.amazon.awssdk.services.s3.presigner.S3Presigner; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * A pre-signed {@link CreateMultipartUploadRequest} that can be executed at a later time without requiring additional signing or * authentication. * * @see S3Presigner#presignCreateMultipartUpload(CreateMultipartUploadPresignRequest) * @see #builder() */ @SdkPublicApi @Immutable @ThreadSafe public class PresignedCreateMultipartUploadRequest extends PresignedRequest implements ToCopyableBuilder<PresignedCreateMultipartUploadRequest.Builder, PresignedCreateMultipartUploadRequest> { private PresignedCreateMultipartUploadRequest(DefaultBuilder builder) { super(builder); } /** * Create a builder that can be used to create a {@link PresignedCreateMultipartUploadRequest}. * * @see S3Presigner#presignCreateMultipartUpload(CreateMultipartUploadPresignRequest) */ public static Builder builder() { return new DefaultBuilder(); } @Override public Builder toBuilder() { return new DefaultBuilder(this); } /** * A builder for a {@link PresignedCreateMultipartUploadRequest}, created with {@link #builder()}. */ @SdkPublicApi @NotThreadSafe public interface Builder extends PresignedRequest.Builder, CopyableBuilder<PresignedCreateMultipartUploadRequest.Builder, PresignedCreateMultipartUploadRequest> { @Override Builder expiration(Instant expiration); @Override Builder isBrowserExecutable(Boolean isBrowserExecutable); @Override Builder signedHeaders(Map<String, List<String>> signedHeaders); @Override Builder signedPayload(SdkBytes signedPayload); @Override Builder httpRequest(SdkHttpRequest httpRequest); @Override PresignedCreateMultipartUploadRequest build(); } @SdkInternalApi private static final class DefaultBuilder extends PresignedRequest.DefaultBuilder<DefaultBuilder> implements Builder { private DefaultBuilder() { } private DefaultBuilder(PresignedCreateMultipartUploadRequest request) { super(request); } @Override public PresignedCreateMultipartUploadRequest build() { return new PresignedCreateMultipartUploadRequest(this); } } }
4,627
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner/model/CompleteMultipartUploadPresignRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.presigner.model; import java.time.Duration; import java.util.function.Consumer; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.awscore.presigner.PresignRequest; import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadRequest; import software.amazon.awssdk.services.s3.presigner.S3Presigner; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * A request to pre-sign a {@link CompleteMultipartUploadRequest} so that it can be executed at a later time without requiring * additional signing or authentication. * * @see S3Presigner#presignCompleteMultipartUpload(CompleteMultipartUploadPresignRequest) * @see #builder() */ @SdkPublicApi @Immutable @ThreadSafe public final class CompleteMultipartUploadPresignRequest extends PresignRequest implements ToCopyableBuilder<CompleteMultipartUploadPresignRequest.Builder, CompleteMultipartUploadPresignRequest> { private final CompleteMultipartUploadRequest completeMultipartUploadRequest; private CompleteMultipartUploadPresignRequest(DefaultBuilder builder) { super(builder); this.completeMultipartUploadRequest = Validate.notNull(builder.completeMultipartUploadRequest, "completeMultipartUploadRequest"); } /** * Create a builder that can be used to create a {@link CompleteMultipartUploadPresignRequest}. * * @see S3Presigner#presignCompleteMultipartUpload(CompleteMultipartUploadPresignRequest) */ public static Builder builder() { return new DefaultBuilder(); } /** * Retrieve the {@link CompleteMultipartUploadRequest} that should be presigned. */ public CompleteMultipartUploadRequest completeMultipartUploadRequest() { return completeMultipartUploadRequest; } @Override public Builder toBuilder() { return new DefaultBuilder(this); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } CompleteMultipartUploadPresignRequest that = (CompleteMultipartUploadPresignRequest) o; return completeMultipartUploadRequest.equals(that.completeMultipartUploadRequest); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + completeMultipartUploadRequest.hashCode(); return result; } /** * A builder for a {@link CompleteMultipartUploadPresignRequest}, created with {@link #builder()}. */ @SdkPublicApi @NotThreadSafe public interface Builder extends PresignRequest.Builder, CopyableBuilder<CompleteMultipartUploadPresignRequest.Builder, CompleteMultipartUploadPresignRequest> { /** * Configure the {@link CompleteMultipartUploadRequest} that should be presigned. */ Builder completeMultipartUploadRequest(CompleteMultipartUploadRequest completeMultipartUploadRequest); /** * Configure the {@link CompleteMultipartUploadRequest} that should be presigned. * <p/> * This is a convenience method for invoking {@link #completeMultipartUploadRequest(CompleteMultipartUploadRequest)} * without needing to invoke {@code CompleteMultipartUploadRequest.builder()} or {@code build()}. */ default Builder completeMultipartUploadRequest( Consumer<CompleteMultipartUploadRequest.Builder> completeMultipartUploadRequest) { CompleteMultipartUploadRequest.Builder builder = CompleteMultipartUploadRequest.builder(); completeMultipartUploadRequest.accept(builder); return completeMultipartUploadRequest(builder.build()); } @Override Builder signatureDuration(Duration signatureDuration); @Override CompleteMultipartUploadPresignRequest build(); } @SdkInternalApi private static final class DefaultBuilder extends PresignRequest.DefaultBuilder<DefaultBuilder> implements Builder { private CompleteMultipartUploadRequest completeMultipartUploadRequest; private DefaultBuilder() { } private DefaultBuilder(CompleteMultipartUploadPresignRequest request) { super(request); this.completeMultipartUploadRequest = request.completeMultipartUploadRequest; } @Override public Builder completeMultipartUploadRequest(CompleteMultipartUploadRequest completeMultipartUploadRequest) { this.completeMultipartUploadRequest = completeMultipartUploadRequest; return this; } @Override public CompleteMultipartUploadPresignRequest build() { return new CompleteMultipartUploadPresignRequest(this); } } }
4,628
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner/model/DeleteObjectPresignRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.presigner.model; import java.time.Duration; import java.util.function.Consumer; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.awscore.presigner.PresignRequest; import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; import software.amazon.awssdk.services.s3.presigner.S3Presigner; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * A request to pre-sign a {@link DeleteObjectRequest} so that it can be executed at a later time without requiring additional * signing or authentication. * * @see S3Presigner#presignDeleteObject(DeleteObjectPresignRequest * @see #builder() */ @SdkPublicApi @Immutable @ThreadSafe public final class DeleteObjectPresignRequest extends PresignRequest implements ToCopyableBuilder<DeleteObjectPresignRequest.Builder, DeleteObjectPresignRequest> { private final DeleteObjectRequest deleteObjectRequest; protected DeleteObjectPresignRequest(DefaultBuilder builder) { super(builder); this.deleteObjectRequest = Validate.notNull(builder.deleteObjectRequest, "deleteObjectRequest"); } /** * Retrieve the {@link DeleteObjectRequest} that should be presigned. */ public DeleteObjectRequest deleteObjectRequest() { return deleteObjectRequest; } @Override public Builder toBuilder() { return new DefaultBuilder(this); } /** * Create a builder that can be used to create a {@link DeleteObjectPresignRequest}. * * @see S3Presigner#presignDeleteObject(DeleteObjectPresignRequest) */ public static Builder builder() { return new DefaultBuilder(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } DeleteObjectPresignRequest that = (DeleteObjectPresignRequest) o; return deleteObjectRequest.equals(that.deleteObjectRequest); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + deleteObjectRequest.hashCode(); return result; } @SdkPublicApi @NotThreadSafe public interface Builder extends PresignRequest.Builder, CopyableBuilder<DeleteObjectPresignRequest.Builder, DeleteObjectPresignRequest> { Builder deleteObjectRequest(DeleteObjectRequest deleteObjectRequest); default Builder deleteObjectRequest(Consumer<DeleteObjectRequest.Builder> deleteObjectRequest) { DeleteObjectRequest.Builder builder = DeleteObjectRequest.builder(); deleteObjectRequest.accept(builder); return deleteObjectRequest(builder.build()); } @Override Builder signatureDuration(Duration signatureDuration); @Override DeleteObjectPresignRequest build(); } @SdkInternalApi private static final class DefaultBuilder extends PresignRequest.DefaultBuilder<DefaultBuilder> implements Builder { private DeleteObjectRequest deleteObjectRequest; private DefaultBuilder() { } private DefaultBuilder(DeleteObjectPresignRequest deleteObjectPresignRequest) { super(deleteObjectPresignRequest); this.deleteObjectRequest = deleteObjectPresignRequest.deleteObjectRequest; } @Override public Builder deleteObjectRequest(DeleteObjectRequest deleteObjectRequest) { this.deleteObjectRequest = deleteObjectRequest; return this; } @Override public DeleteObjectPresignRequest build() { return new DeleteObjectPresignRequest(this); } } }
4,629
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner/model/CreateMultipartUploadPresignRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.presigner.model; import java.time.Duration; import java.util.function.Consumer; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.awscore.presigner.PresignRequest; import software.amazon.awssdk.services.s3.model.CreateMultipartUploadRequest; import software.amazon.awssdk.services.s3.presigner.S3Presigner; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * A request to pre-sign a {@link CreateMultipartUploadRequest} so that it can be executed at a later time without requiring * additional signing or authentication. * * @see S3Presigner#presignCreateMultipartUpload(CreateMultipartUploadPresignRequest) * @see #builder() */ @SdkPublicApi @Immutable @ThreadSafe public final class CreateMultipartUploadPresignRequest extends PresignRequest implements ToCopyableBuilder<CreateMultipartUploadPresignRequest.Builder, CreateMultipartUploadPresignRequest> { private final CreateMultipartUploadRequest createMultipartUploadRequest; private CreateMultipartUploadPresignRequest(DefaultBuilder builder) { super(builder); this.createMultipartUploadRequest = Validate.notNull(builder.createMultipartUploadRequest, "createMultipartUploadRequest"); } /** * Create a builder that can be used to create a {@link CreateMultipartUploadPresignRequest}. * * @see S3Presigner#presignCreateMultipartUpload(CreateMultipartUploadPresignRequest) */ public static Builder builder() { return new DefaultBuilder(); } /** * Retrieve the {@link CreateMultipartUploadRequest} that should be presigned. */ public CreateMultipartUploadRequest createMultipartUploadRequest() { return createMultipartUploadRequest; } @Override public Builder toBuilder() { return new DefaultBuilder(this); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } CreateMultipartUploadPresignRequest that = (CreateMultipartUploadPresignRequest) o; return createMultipartUploadRequest.equals(that.createMultipartUploadRequest); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + createMultipartUploadRequest.hashCode(); return result; } /** * A builder for a {@link CreateMultipartUploadPresignRequest}, created with {@link #builder()}. */ @SdkPublicApi @NotThreadSafe public interface Builder extends PresignRequest.Builder, CopyableBuilder<CreateMultipartUploadPresignRequest.Builder, CreateMultipartUploadPresignRequest> { /** * Configure the {@link CreateMultipartUploadRequest} that should be presigned. */ Builder createMultipartUploadRequest(CreateMultipartUploadRequest createMultipartUploadRequest); /** * Configure the {@link CreateMultipartUploadRequest} that should be presigned. * <p/> * This is a convenience method for invoking {@link #createMultipartUploadRequest(CreateMultipartUploadRequest)} * without needing to invoke {@code CreateMultipartUploadRequest.builder()} or {@code build()}. */ default Builder createMultipartUploadRequest( Consumer<CreateMultipartUploadRequest.Builder> createMultipartUploadRequest) { CreateMultipartUploadRequest.Builder builder = CreateMultipartUploadRequest.builder(); createMultipartUploadRequest.accept(builder); return createMultipartUploadRequest(builder.build()); } @Override Builder signatureDuration(Duration signatureDuration); @Override CreateMultipartUploadPresignRequest build(); } @SdkInternalApi private static final class DefaultBuilder extends PresignRequest.DefaultBuilder<DefaultBuilder> implements Builder { private CreateMultipartUploadRequest createMultipartUploadRequest; private DefaultBuilder() { } private DefaultBuilder(CreateMultipartUploadPresignRequest request) { super(request); this.createMultipartUploadRequest = request.createMultipartUploadRequest; } @Override public Builder createMultipartUploadRequest(CreateMultipartUploadRequest createMultipartUploadRequest) { this.createMultipartUploadRequest = createMultipartUploadRequest; return this; } @Override public CreateMultipartUploadPresignRequest build() { return new CreateMultipartUploadPresignRequest(this); } } }
4,630
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner/model/PutObjectPresignRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.presigner.model; import java.time.Duration; import java.util.function.Consumer; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.awscore.presigner.PresignRequest; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.presigner.S3Presigner; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * A request to pre-sign a {@link PutObjectRequest} so that it can be executed at a later time without requiring additional * signing or authentication. * * @see S3Presigner#presignPutObject(PutObjectPresignRequest) * @see #builder() */ @SdkPublicApi @Immutable @ThreadSafe public final class PutObjectPresignRequest extends PresignRequest implements ToCopyableBuilder<PutObjectPresignRequest.Builder, PutObjectPresignRequest> { private final PutObjectRequest putObjectRequest; private PutObjectPresignRequest(DefaultBuilder builder) { super(builder); this.putObjectRequest = Validate.notNull(builder.putObjectRequest, "putObjectRequest"); } /** * Create a builder that can be used to create a {@link PutObjectPresignRequest}. * * @see S3Presigner#presignPutObject(PutObjectPresignRequest) */ public static Builder builder() { return new DefaultBuilder(); } /** * Retrieve the {@link PutObjectRequest} that should be presigned. */ public PutObjectRequest putObjectRequest() { return putObjectRequest; } @Override public Builder toBuilder() { return new DefaultBuilder(this); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } PutObjectPresignRequest that = (PutObjectPresignRequest) o; return putObjectRequest.equals(that.putObjectRequest); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + putObjectRequest.hashCode(); return result; } /** * A builder for a {@link PutObjectPresignRequest}, created with {@link #builder()}. */ @SdkPublicApi @NotThreadSafe public interface Builder extends PresignRequest.Builder, CopyableBuilder<PutObjectPresignRequest.Builder, PutObjectPresignRequest> { /** * Configure the {@link PutObjectRequest} that should be presigned. */ Builder putObjectRequest(PutObjectRequest putObjectRequest); /** * Configure the {@link PutObjectRequest} that should be presigned. * <p/> * This is a convenience method for invoking {@link #putObjectRequest(PutObjectRequest)} without needing to invoke * {@code PutObjectRequest.builder()} or {@code build()}. */ default Builder putObjectRequest(Consumer<PutObjectRequest.Builder> putObjectRequest) { PutObjectRequest.Builder builder = PutObjectRequest.builder(); putObjectRequest.accept(builder); return putObjectRequest(builder.build()); } @Override Builder signatureDuration(Duration signatureDuration); @Override PutObjectPresignRequest build(); } @SdkInternalApi private static final class DefaultBuilder extends PresignRequest.DefaultBuilder<DefaultBuilder> implements Builder { private PutObjectRequest putObjectRequest; private DefaultBuilder() { } private DefaultBuilder(PutObjectPresignRequest request) { super(request); this.putObjectRequest = request.putObjectRequest; } @Override public Builder putObjectRequest(PutObjectRequest putObjectRequest) { this.putObjectRequest = putObjectRequest; return this; } @Override public PutObjectPresignRequest build() { return new PutObjectPresignRequest(this); } } }
4,631
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner/model/PresignedGetObjectRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.presigner.model; import java.time.Instant; import java.util.List; import java.util.Map; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.awscore.presigner.PresignedRequest; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.s3.presigner.S3Presigner; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * A pre-signed a {@link GetObjectRequest} that can be executed at a later time without requiring additional signing or * authentication. * * @see S3Presigner#presignGetObject(GetObjectPresignRequest) * @see #builder() */ @SdkPublicApi @Immutable @ThreadSafe public class PresignedGetObjectRequest extends PresignedRequest implements ToCopyableBuilder<PresignedGetObjectRequest.Builder, PresignedGetObjectRequest> { private PresignedGetObjectRequest(DefaultBuilder builder) { super(builder); } /** * Create a builder that can be used to create a {@link PresignedGetObjectRequest}. * * @see S3Presigner#presignGetObject(GetObjectPresignRequest) */ public static Builder builder() { return new DefaultBuilder(); } @Override public Builder toBuilder() { return new DefaultBuilder(this); } /** * A builder for a {@link PresignedGetObjectRequest}, created with {@link #builder()}. */ @SdkPublicApi @NotThreadSafe public interface Builder extends PresignedRequest.Builder, CopyableBuilder<PresignedGetObjectRequest.Builder, PresignedGetObjectRequest> { @Override Builder expiration(Instant expiration); @Override Builder isBrowserExecutable(Boolean isBrowserExecutable); @Override Builder signedHeaders(Map<String, List<String>> signedHeaders); @Override Builder signedPayload(SdkBytes signedPayload); @Override Builder httpRequest(SdkHttpRequest httpRequest); @Override PresignedGetObjectRequest build(); } @SdkInternalApi private static final class DefaultBuilder extends PresignedRequest.DefaultBuilder<DefaultBuilder> implements Builder { private DefaultBuilder() { } private DefaultBuilder(PresignedGetObjectRequest request) { super(request); } @Override public PresignedGetObjectRequest build() { return new PresignedGetObjectRequest(this); } } }
4,632
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner/model/PresignedAbortMultipartUploadRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.presigner.model; import java.time.Instant; import java.util.List; import java.util.Map; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.awscore.presigner.PresignedRequest; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.services.s3.model.AbortMultipartUploadRequest; import software.amazon.awssdk.services.s3.presigner.S3Presigner; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * A pre-signed {@link AbortMultipartUploadRequest} that can be executed at a later time without requiring additional signing * or authentication. * * @see S3Presigner#presignAbortMultipartUpload(AbortMultipartUploadPresignRequest) * @see #builder() */ @SdkPublicApi @Immutable @ThreadSafe public class PresignedAbortMultipartUploadRequest extends PresignedRequest implements ToCopyableBuilder<PresignedAbortMultipartUploadRequest.Builder, PresignedAbortMultipartUploadRequest> { private PresignedAbortMultipartUploadRequest(DefaultBuilder builder) { super(builder); } /** * Create a builder that can be used to create a {@link PresignedAbortMultipartUploadRequest}. * * @see S3Presigner#presignAbortMultipartUpload(AbortMultipartUploadPresignRequest) */ public static Builder builder() { return new DefaultBuilder(); } @Override public Builder toBuilder() { return new DefaultBuilder(this); } /** * A builder for a {@link PresignedAbortMultipartUploadRequest}, created with {@link #builder()}. */ @SdkPublicApi @NotThreadSafe public interface Builder extends PresignedRequest.Builder, CopyableBuilder<PresignedAbortMultipartUploadRequest.Builder, PresignedAbortMultipartUploadRequest> { @Override Builder expiration(Instant expiration); @Override Builder isBrowserExecutable(Boolean isBrowserExecutable); @Override Builder signedHeaders(Map<String, List<String>> signedHeaders); @Override Builder signedPayload(SdkBytes signedPayload); @Override Builder httpRequest(SdkHttpRequest httpRequest); @Override PresignedAbortMultipartUploadRequest build(); } @SdkInternalApi private static final class DefaultBuilder extends PresignedRequest.DefaultBuilder<DefaultBuilder> implements Builder { private DefaultBuilder() { } private DefaultBuilder(PresignedAbortMultipartUploadRequest request) { super(request); } @Override public PresignedAbortMultipartUploadRequest build() { return new PresignedAbortMultipartUploadRequest(this); } } }
4,633
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner/model/AbortMultipartUploadPresignRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.presigner.model; import java.time.Duration; import java.util.function.Consumer; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.awscore.presigner.PresignRequest; import software.amazon.awssdk.services.s3.model.AbortMultipartUploadRequest; import software.amazon.awssdk.services.s3.presigner.S3Presigner; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * A request to pre-sign a {@link AbortMultipartUploadRequest} so that it can be executed at a later time without requiring * additional signing or authentication. * * @see S3Presigner#presignAbortMultipartUpload(AbortMultipartUploadPresignRequest) * @see #builder() */ @SdkPublicApi @Immutable @ThreadSafe public final class AbortMultipartUploadPresignRequest extends PresignRequest implements ToCopyableBuilder<AbortMultipartUploadPresignRequest.Builder, AbortMultipartUploadPresignRequest> { private final AbortMultipartUploadRequest abortMultipartUploadRequest; private AbortMultipartUploadPresignRequest(DefaultBuilder builder) { super(builder); this.abortMultipartUploadRequest = Validate.notNull(builder.abortMultipartUploadRequest, "abortMultipartUploadRequest"); } /** * Create a builder that can be used to create a {@link AbortMultipartUploadPresignRequest}. * * @see S3Presigner#presignAbortMultipartUpload(AbortMultipartUploadPresignRequest) */ public static Builder builder() { return new DefaultBuilder(); } /** * Retrieve the {@link AbortMultipartUploadRequest} that should be presigned. */ public AbortMultipartUploadRequest abortMultipartUploadRequest() { return abortMultipartUploadRequest; } @Override public Builder toBuilder() { return new DefaultBuilder(this); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } AbortMultipartUploadPresignRequest that = (AbortMultipartUploadPresignRequest) o; return abortMultipartUploadRequest.equals(that.abortMultipartUploadRequest); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + abortMultipartUploadRequest.hashCode(); return result; } /** * A builder for a {@link AbortMultipartUploadPresignRequest}, created with {@link #builder()}. */ @SdkPublicApi @NotThreadSafe public interface Builder extends PresignRequest.Builder, CopyableBuilder<AbortMultipartUploadPresignRequest.Builder, AbortMultipartUploadPresignRequest> { /** * Configure the {@link AbortMultipartUploadRequest} that should be presigned. */ Builder abortMultipartUploadRequest(AbortMultipartUploadRequest abortMultipartUploadRequest); /** * Configure the {@link AbortMultipartUploadRequest} that should be presigned. * <p/> * This is a convenience method for invoking {@link #abortMultipartUploadRequest(AbortMultipartUploadRequest)} * without needing to invoke {@code AbortMultipartUploadRequest.builder()} or {@code build()}. */ default Builder abortMultipartUploadRequest(Consumer<AbortMultipartUploadRequest.Builder> abortMultipartUploadRequest) { AbortMultipartUploadRequest.Builder builder = AbortMultipartUploadRequest.builder(); abortMultipartUploadRequest.accept(builder); return abortMultipartUploadRequest(builder.build()); } @Override Builder signatureDuration(Duration signatureDuration); @Override AbortMultipartUploadPresignRequest build(); } @SdkInternalApi private static final class DefaultBuilder extends PresignRequest.DefaultBuilder<DefaultBuilder> implements Builder { private AbortMultipartUploadRequest abortMultipartUploadRequest; private DefaultBuilder() { } private DefaultBuilder(AbortMultipartUploadPresignRequest request) { super(request); this.abortMultipartUploadRequest = request.abortMultipartUploadRequest; } @Override public Builder abortMultipartUploadRequest(AbortMultipartUploadRequest abortMultipartUploadRequest) { this.abortMultipartUploadRequest = abortMultipartUploadRequest; return this; } @Override public AbortMultipartUploadPresignRequest build() { return new AbortMultipartUploadPresignRequest(this); } } }
4,634
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/model/GetUrlRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.model; import java.net.URI; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.function.BiConsumer; import java.util.function.Function; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.protocol.MarshallLocation; import software.amazon.awssdk.core.protocol.MarshallingType; import software.amazon.awssdk.core.traits.LocationTrait; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * Request to generate a URL representing an object in Amazon S3. * * If the object identified by the given bucket and key has public read permissions, * then this URL can be directly accessed to retrieve the object's data. */ @SdkPublicApi public final class GetUrlRequest implements SdkPojo, ToCopyableBuilder<GetUrlRequest.Builder, GetUrlRequest> { private static final SdkField<String> BUCKET_FIELD = SdkField .builder(MarshallingType.STRING) .getter(getter(GetUrlRequest::bucket)) .setter(setter(Builder::bucket)) .traits(LocationTrait.builder().location(MarshallLocation.PATH).locationName("Bucket") .unmarshallLocationName("Bucket").build()).build(); private static final SdkField<String> KEY_FIELD = SdkField .builder(MarshallingType.STRING) .getter(getter(GetUrlRequest::key)) .setter(setter(Builder::key)) .traits(LocationTrait.builder().location(MarshallLocation.GREEDY_PATH).locationName("Key") .unmarshallLocationName("Key").build()).build(); private static final SdkField<String> VERSION_ID_FIELD = SdkField .builder(MarshallingType.STRING) .memberName("VersionId") .getter(getter(GetUrlRequest::versionId)) .setter(setter(Builder::versionId)) .traits(LocationTrait.builder().location(MarshallLocation.QUERY_PARAM).locationName("versionId") .unmarshallLocationName("versionId").build()).build(); private static final List<SdkField<?>> SDK_FIELDS = Collections.unmodifiableList(Arrays.asList(BUCKET_FIELD, KEY_FIELD, VERSION_ID_FIELD)); private final String bucket; private final String key; private final Region region; private final URI endpoint; private final String versionId; private GetUrlRequest(BuilderImpl builder) { this.bucket = Validate.paramNotBlank(builder.bucket, "Bucket"); this.key = Validate.paramNotBlank(builder.key, "Key"); this.region = builder.region; this.endpoint = builder.endpoint; this.versionId = builder.versionId; } /** * @return The name of the bucket for the object */ public String bucket() { return bucket; } /** * @return The key value for this object. */ public String key() { return key; } /** * @return The region value to use for constructing the URL */ public Region region() { return region; } /** * @return The endpoint value to use for constructing the URL */ public URI endpoint() { return endpoint; } /** * VersionId used to reference a specific version of the object. * * @return VersionId used to reference a specific version of the object. */ public String versionId() { return versionId; } @Override public Builder toBuilder() { return new BuilderImpl(this); } public static Builder builder() { return new BuilderImpl(); } public <T> Optional<T> getValueForField(String fieldName, Class<T> clazz) { switch (fieldName) { case "Bucket": return Optional.ofNullable(clazz.cast(bucket())); case "Key": return Optional.ofNullable(clazz.cast(key())); case "VersionId": return Optional.ofNullable(clazz.cast(versionId())); default: return Optional.empty(); } } @Override public List<SdkField<?>> sdkFields() { return SDK_FIELDS; } private static <T> Function<Object, T> getter(Function<GetUrlRequest, T> g) { return obj -> g.apply((GetUrlRequest) obj); } private static <T> BiConsumer<Object, T> setter(BiConsumer<Builder, T> s) { return (obj, val) -> s.accept((Builder) obj, val); } public interface Builder extends SdkPojo, CopyableBuilder<Builder, GetUrlRequest> { /** * Sets the value of the Bucket property for this object. * * @param bucket * The new value for the Bucket property for this object. * @return Returns a reference to this object so that method calls can be chained together. */ Builder bucket(String bucket); /** * Sets the value of the Key property for this object. * * @param key * The new value for the Key property for this object. * @return Returns a reference to this object so that method calls can be chained together. */ Builder key(String key); /** * VersionId used to reference a specific version of the object. * * @param versionId * VersionId used to reference a specific version of the object. * @return Returns a reference to this object so that method calls can be chained together. */ Builder versionId(String versionId); /** * Sets the region to use for constructing the URL. * * @param region * The region to use for constructing the URL. * @return Returns a reference to this object so that method calls can be chained together. */ Builder region(Region region); /** * Sets the endpoint to use for constructing the URL. * * @param endpoint * The endpoint to use for constructing the URL. * @return Returns a reference to this object so that method calls can be chained together. */ Builder endpoint(URI endpoint); } private static final class BuilderImpl implements Builder { private String bucket; private String key; private Region region; private URI endpoint; private String versionId; private BuilderImpl() { } private BuilderImpl(GetUrlRequest getUrlRequest) { bucket(getUrlRequest.bucket); key(getUrlRequest.key); region(getUrlRequest.region); endpoint(getUrlRequest.endpoint); } @Override public Builder bucket(String bucket) { this.bucket = bucket; return this; } @Override public Builder key(String key) { this.key = key; return this; } @Override public Builder versionId(String versionId) { this.versionId = versionId; return this; } @Override public Builder region(Region region) { this.region = region; return this; } @Override public Builder endpoint(URI endpoint) { this.endpoint = endpoint; return this; } @Override public GetUrlRequest build() { return new GetUrlRequest(this); } @Override public List<SdkField<?>> sdkFields() { return SDK_FIELDS; } } }
4,635
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/crt/S3CrtRetryConfiguration.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.crt; import java.util.Objects; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.services.s3.S3CrtAsyncClientBuilder; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * Retry option configuration for AWS CRT-based S3 client. * * @see S3CrtAsyncClientBuilder#retryConfiguration */ @SdkPublicApi @Immutable @ThreadSafe public final class S3CrtRetryConfiguration implements ToCopyableBuilder<S3CrtRetryConfiguration.Builder, S3CrtRetryConfiguration> { private final Integer numRetries; private S3CrtRetryConfiguration(DefaultBuilder builder) { Validate.notNull(builder.numRetries, "numRetries"); this.numRetries = builder.numRetries; } /** * Creates a default builder for {@link S3CrtRetryConfiguration}. */ public static Builder builder() { return new S3CrtRetryConfiguration.DefaultBuilder(); } /** * Retrieve the {@link S3CrtRetryConfiguration.Builder#numRetries(Integer)} configured on the builder. */ public Integer numRetries() { return numRetries; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } S3CrtRetryConfiguration that = (S3CrtRetryConfiguration) o; return Objects.equals(numRetries, that.numRetries); } @Override public int hashCode() { return numRetries != null ? numRetries.hashCode() : 0; } @Override public Builder toBuilder() { return new S3CrtRetryConfiguration.DefaultBuilder(this); } public interface Builder extends CopyableBuilder<S3CrtRetryConfiguration.Builder, S3CrtRetryConfiguration> { /** * Sets the maximum number of retries for a single HTTP request. * <p> For example, if an upload operation is split into 5 HTTP service requests ( One for initiate, Three for * uploadPart and one for completeUpload), then numRetries specifies the maximum number of retries for each failed * request, not for the entire uploadObject operation. * * @param numRetries The maximum number of retries for a single HTTP request. * @return The builder of the method chaining. */ Builder numRetries(Integer numRetries); } private static final class DefaultBuilder implements Builder { private Integer numRetries; private DefaultBuilder() { } private DefaultBuilder(S3CrtRetryConfiguration crtRetryConfiguration) { this.numRetries = crtRetryConfiguration.numRetries; } @Override public Builder numRetries(Integer numRetries) { this.numRetries = numRetries; return this; } @Override public S3CrtRetryConfiguration build() { return new S3CrtRetryConfiguration(this); } } }
4,636
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/crt/S3CrtSdkHttpExecutionAttribute.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.crt; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.async.listener.PublisherListener; import software.amazon.awssdk.http.SdkHttpExecutionAttribute; import software.amazon.awssdk.services.s3.internal.crt.S3MetaRequestPauseObservable; @SdkProtectedApi public final class S3CrtSdkHttpExecutionAttribute<T> extends SdkHttpExecutionAttribute<T> { public static final S3CrtSdkHttpExecutionAttribute<S3MetaRequestPauseObservable> METAREQUEST_PAUSE_OBSERVABLE = new S3CrtSdkHttpExecutionAttribute<>(S3MetaRequestPauseObservable.class); public static final S3CrtSdkHttpExecutionAttribute<PublisherListener> CRT_PROGRESS_LISTENER = new S3CrtSdkHttpExecutionAttribute<>(PublisherListener.class); private S3CrtSdkHttpExecutionAttribute(Class<T> valueClass) { super(valueClass); } }
4,637
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/crt/S3CrtProxyConfiguration.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.crt; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.crtcore.CrtProxyConfiguration; import software.amazon.awssdk.services.s3.S3CrtAsyncClientBuilder; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * Proxy configuration for {@link S3CrtAsyncClientBuilder}. This class is used to configure proxy to be used * by the AWS CRT-based S3 client. * * @see S3CrtHttpConfiguration.Builder#proxyConfiguration(S3CrtProxyConfiguration) */ @SdkPublicApi @Immutable @ThreadSafe public final class S3CrtProxyConfiguration extends CrtProxyConfiguration implements ToCopyableBuilder<S3CrtProxyConfiguration.Builder, S3CrtProxyConfiguration> { private S3CrtProxyConfiguration(DefaultBuilder builder) { super(builder); } @Override public Builder toBuilder() { return new DefaultBuilder(this); } public static Builder builder() { return new DefaultBuilder(); } @Override public String toString() { return super.toString(); } @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(Object o) { return super.equals(o); } /** * Builder for {@link S3CrtProxyConfiguration}. */ public interface Builder extends CrtProxyConfiguration.Builder, CopyableBuilder<Builder, S3CrtProxyConfiguration> { @Override Builder host(String host); @Override Builder port(int port); @Override Builder scheme(String scheme); @Override Builder username(String username); @Override Builder password(String password); @Override Builder useSystemPropertyValues(Boolean useSystemPropertyValues); @Override Builder useEnvironmentVariableValues(Boolean useEnvironmentVariableValues); @Override S3CrtProxyConfiguration build(); } private static final class DefaultBuilder extends CrtProxyConfiguration.DefaultBuilder<DefaultBuilder> implements Builder { private DefaultBuilder(S3CrtProxyConfiguration proxyConfiguration) { super(proxyConfiguration); } private DefaultBuilder() { } @Override public S3CrtProxyConfiguration build() { return new S3CrtProxyConfiguration(this); } } }
4,638
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/crt/S3CrtHttpConfiguration.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.crt; import java.time.Duration; import java.util.Objects; import java.util.function.Consumer; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.services.s3.S3CrtAsyncClientBuilder; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * HTTP configuration for AWS CRT-based S3 client. * * @see S3CrtAsyncClientBuilder#httpConfiguration */ @SdkPublicApi @Immutable @ThreadSafe public final class S3CrtHttpConfiguration implements ToCopyableBuilder<S3CrtHttpConfiguration.Builder, S3CrtHttpConfiguration> { private final Duration connectionTimeout; private final S3CrtProxyConfiguration proxyConfiguration; private final S3CrtConnectionHealthConfiguration healthConfiguration; private final Boolean trustAllCertificatesEnabled; private S3CrtHttpConfiguration(DefaultBuilder builder) { this.connectionTimeout = builder.connectionTimeout; this.proxyConfiguration = builder.proxyConfiguration; this.healthConfiguration = builder.healthConfiguration; this.trustAllCertificatesEnabled = builder.trustAllCertificatesEnabled; } /** * Creates a default builder for {@link S3CrtHttpConfiguration}. */ public static Builder builder() { return new S3CrtHttpConfiguration.DefaultBuilder(); } /** * Return the amount of time to wait when initially establishing a connection before giving up and timing out. */ public Duration connectionTimeout() { return connectionTimeout; } /** * Return the configured {@link S3CrtProxyConfiguration}. */ public S3CrtProxyConfiguration proxyConfiguration() { return proxyConfiguration; } /** * Return the configured {@link S3CrtConnectionHealthConfiguration}. */ public S3CrtConnectionHealthConfiguration healthConfiguration() { return healthConfiguration; } /** * Return the configured {@link Builder#trustAllCertificatesEnabled}. */ public Boolean trustAllCertificatesEnabled() { return trustAllCertificatesEnabled; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } S3CrtHttpConfiguration that = (S3CrtHttpConfiguration) o; if (!Objects.equals(connectionTimeout, that.connectionTimeout)) { return false; } if (!Objects.equals(proxyConfiguration, that.proxyConfiguration)) { return false; } if (!Objects.equals(healthConfiguration, that.healthConfiguration)) { return false; } return Objects.equals(trustAllCertificatesEnabled, that.trustAllCertificatesEnabled); } @Override public int hashCode() { int result = connectionTimeout != null ? connectionTimeout.hashCode() : 0; result = 31 * result + (proxyConfiguration != null ? proxyConfiguration.hashCode() : 0); result = 31 * result + (healthConfiguration != null ? healthConfiguration.hashCode() : 0); result = 31 * result + (trustAllCertificatesEnabled != null ? trustAllCertificatesEnabled.hashCode() : 0); return result; } @Override public Builder toBuilder() { return new S3CrtHttpConfiguration.DefaultBuilder(this); } public interface Builder extends CopyableBuilder<S3CrtHttpConfiguration.Builder, S3CrtHttpConfiguration> { /** * The amount of time to wait when initially establishing a connection before giving up and timing out. * * @param connectionTimeout timeout * @return The builder of the method chaining. */ Builder connectionTimeout(Duration connectionTimeout); /** * <p> * Option to disable SSL cert validation and SSL host name verification. * This turns off x.509 validation. * By default, this option is off. * Only enable this option for testing purposes. * @param trustAllCertificatesEnabled True if SSL cert validation is disabled. * @return The builder of the method chaining. */ Builder trustAllCertificatesEnabled(Boolean trustAllCertificatesEnabled); /** * Sets the http proxy configuration to use for this client. * * @param proxyConfiguration The http proxy configuration to use * @return The builder of the method chaining. */ Builder proxyConfiguration(S3CrtProxyConfiguration proxyConfiguration); /** * A convenience method that creates an instance of the {@link S3CrtProxyConfiguration} builder, avoiding the * need to create one manually via {@link S3CrtProxyConfiguration#builder()}. * * @param configurationBuilder The config builder to use * @return The builder of the method chaining. * @see #proxyConfiguration(S3CrtProxyConfiguration) */ Builder proxyConfiguration(Consumer<S3CrtProxyConfiguration.Builder> configurationBuilder); /** * Configure the health checks for all connections established by this client. * * <p> * You can set a throughput threshold for a connection to be considered healthy. If a connection falls below this * threshold ({@link S3CrtConnectionHealthConfiguration#minimumThroughputInBps() }) for the configurable amount of time * ({@link S3CrtConnectionHealthConfiguration#minimumThroughputTimeout()}), then the connection is considered unhealthy * and will be shut down. * * @param healthConfiguration The health checks config to use * @return The builder of the method chaining. */ Builder connectionHealthConfiguration(S3CrtConnectionHealthConfiguration healthConfiguration); /** * A convenience method that creates an instance of the {@link S3CrtConnectionHealthConfiguration} builder, avoiding the * need to create one manually via {@link S3CrtConnectionHealthConfiguration#builder()}. * * @param configurationBuilder The health checks config builder to use * @return The builder of the method chaining. * @see #connectionHealthConfiguration(S3CrtConnectionHealthConfiguration) */ Builder connectionHealthConfiguration(Consumer<S3CrtConnectionHealthConfiguration.Builder> configurationBuilder); @Override S3CrtHttpConfiguration build(); } private static final class DefaultBuilder implements Builder { private S3CrtConnectionHealthConfiguration healthConfiguration; private Duration connectionTimeout; private Boolean trustAllCertificatesEnabled; private S3CrtProxyConfiguration proxyConfiguration; private DefaultBuilder() { } private DefaultBuilder(S3CrtHttpConfiguration httpConfiguration) { this.healthConfiguration = httpConfiguration.healthConfiguration; this.connectionTimeout = httpConfiguration.connectionTimeout; this.proxyConfiguration = httpConfiguration.proxyConfiguration; this.trustAllCertificatesEnabled = httpConfiguration.trustAllCertificatesEnabled; } @Override public Builder connectionTimeout(Duration connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } @Override public Builder trustAllCertificatesEnabled(Boolean trustAllCertificatesEnabled) { this.trustAllCertificatesEnabled = trustAllCertificatesEnabled; return this; } @Override public Builder proxyConfiguration(S3CrtProxyConfiguration proxyConfiguration) { this.proxyConfiguration = proxyConfiguration; return this; } @Override public Builder proxyConfiguration(Consumer<S3CrtProxyConfiguration.Builder> configurationBuilder) { return proxyConfiguration(S3CrtProxyConfiguration.builder() .applyMutation(configurationBuilder) .build()); } @Override public Builder connectionHealthConfiguration(S3CrtConnectionHealthConfiguration healthConfiguration) { this.healthConfiguration = healthConfiguration; return this; } @Override public Builder connectionHealthConfiguration(Consumer<S3CrtConnectionHealthConfiguration.Builder> configurationBuilder) { return connectionHealthConfiguration(S3CrtConnectionHealthConfiguration.builder() .applyMutation(configurationBuilder) .build()); } @Override public S3CrtHttpConfiguration build() { return new S3CrtHttpConfiguration(this); } } }
4,639
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/crt/S3CrtConnectionHealthConfiguration.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.crt; import java.time.Duration; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.crtcore.CrtConnectionHealthConfiguration; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * Configuration that defines health checks for all connections established by * the AWS CRT-based S3 client * */ @SdkPublicApi @Immutable @ThreadSafe public final class S3CrtConnectionHealthConfiguration extends CrtConnectionHealthConfiguration implements ToCopyableBuilder<S3CrtConnectionHealthConfiguration.Builder, S3CrtConnectionHealthConfiguration> { private S3CrtConnectionHealthConfiguration(DefaultBuilder builder) { super(builder); } public static Builder builder() { return new DefaultBuilder(); } @Override public Builder toBuilder() { return new DefaultBuilder(this); } @Override public boolean equals(Object o) { return super.equals(o); } @Override public int hashCode() { return super.hashCode(); } /** * A builder for {@link S3CrtConnectionHealthConfiguration}. * * <p>All implementations of this interface are mutable and not thread safe.</p> */ public interface Builder extends CrtConnectionHealthConfiguration.Builder, CopyableBuilder<Builder, S3CrtConnectionHealthConfiguration> { @Override Builder minimumThroughputInBps(Long minimumThroughputInBps); @Override Builder minimumThroughputTimeout(Duration minimumThroughputTimeout); @Override S3CrtConnectionHealthConfiguration build(); } private static final class DefaultBuilder extends CrtConnectionHealthConfiguration.DefaultBuilder<DefaultBuilder> implements Builder { private DefaultBuilder() { } private DefaultBuilder(S3CrtConnectionHealthConfiguration configuration) { super(configuration); } @Override public S3CrtConnectionHealthConfiguration build() { return new S3CrtConnectionHealthConfiguration(this); } } }
4,640
0
Create_ds/aws-sdk-java-v2/services/emr/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/emr/src/it/java/software/amazon/awssdk/services/emr/EMRIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.emr; import java.time.Duration; import java.time.Instant; import org.junit.After; import org.junit.Test; import software.amazon.awssdk.services.emr.model.ListClustersRequest; import software.amazon.awssdk.services.emr.model.TerminateJobFlowsRequest; /** Integration test for basic service operations. */ public class EMRIntegrationTest extends IntegrationTestBase { private String jobFlowId; /** * Cleans up any created tests resources. */ @After public void tearDown() throws Exception { try { if (jobFlowId != null) { emr.terminateJobFlows(TerminateJobFlowsRequest.builder().jobFlowIds(jobFlowId).build()); } } catch (Exception e) { e.printStackTrace(); } } // See https://forums.aws.amazon.com/thread.jspa?threadID=158756 @Test public void testListCluster() { emr.listClusters(ListClustersRequest.builder() .createdAfter(Instant.now().minus(Duration.ofDays(1))) .build()); } }
4,641
0
Create_ds/aws-sdk-java-v2/services/emr/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/emr/src/it/java/software/amazon/awssdk/services/emr/IntegrationTestBase.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.emr; import java.io.FileNotFoundException; import java.io.IOException; import org.junit.BeforeClass; import software.amazon.awssdk.testutils.service.AwsTestBase; /** * Base class for EMR integration tests. Provides convenience methods for * creating test data, and automatically loads AWS credentials from a properties * file on disk and instantiates clients for the individual tests to use. */ public class IntegrationTestBase extends AwsTestBase { /** The EMR client for all tests to use. */ protected static EmrClient emr; /** * Loads the AWS account info for the integration tests and creates an * EMR client for tests to use. */ @BeforeClass public static void setUp() throws FileNotFoundException, IOException { setUpCredentials(); emr = EmrClient.builder().credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build(); } }
4,642
0
Create_ds/aws-sdk-java-v2/services/sns/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/sns/src/test/java/software/amazon/awssdk/services/sns/SnsSignatureCheckerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.sns; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.net.URISyntaxException; import java.security.PublicKey; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import org.junit.jupiter.api.Test; import software.amazon.awssdk.testutils.service.AwsTestBase; public class SnsSignatureCheckerTest extends AwsTestBase { @Test public void validateMessageTest() throws Exception { final String jsonMessage = getResourceAsString(getClass(), SnsTestResources.SAMPLE_MESSAGE); SignatureChecker checker = new SignatureChecker(); assertTrue(checker.verifyMessageSignature(jsonMessage, getPublicKey())); } private PublicKey getPublicKey() throws URISyntaxException, IOException, CertificateException { CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate cert = (X509Certificate) cf .generateCertificate(getClass().getResourceAsStream(SnsTestResources.FIXED_PUBLIC_CERT)); return cert.getPublicKey(); } }
4,643
0
Create_ds/aws-sdk-java-v2/services/sns/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/sns/src/test/java/software/amazon/awssdk/services/sns/SnsTestResources.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.sns; /** * Constants for test resource locations */ public class SnsTestResources { public static final String PACKAGE_ROOT = "/software/amazon/awssdk/services/sns/"; /** * A sample notification message from SNS */ public static final String SAMPLE_MESSAGE = PACKAGE_ROOT + "sample-message.json"; /** * Public cert used to verify message authenticity. Fixed for unit tests. */ public static final String FIXED_PUBLIC_CERT = PACKAGE_ROOT + "unit-test-public-cert.pem"; }
4,644
0
Create_ds/aws-sdk-java-v2/services/sns/src/it/java/software/amazon/awssdk/core/auth
Create_ds/aws-sdk-java-v2/services/sns/src/it/java/software/amazon/awssdk/core/auth/policy/SnsPolicyIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.auth.policy; import org.junit.After; import org.junit.Test; import software.amazon.awssdk.core.auth.policy.Statement.Effect; import software.amazon.awssdk.core.auth.policy.conditions.StringCondition; import software.amazon.awssdk.core.auth.policy.conditions.StringCondition.StringComparisonType; import software.amazon.awssdk.services.sns.IntegrationTestBase; import software.amazon.awssdk.services.sns.model.CreateTopicRequest; import software.amazon.awssdk.services.sns.model.DeleteTopicRequest; import software.amazon.awssdk.services.sns.model.SetTopicAttributesRequest; /** * Integration tests for the service specific access control policy code provided by the Sns client. */ public class SnsPolicyIntegrationTest extends IntegrationTestBase { private String topicArn; /** * Releases all test resources. */ @After public void tearDown() throws Exception { sns.deleteTopic(DeleteTopicRequest.builder().topicArn(topicArn).build()); } /** * Tests that we can construct valid policies with Sns specific conditions/resources/etc. */ @Test public void testPolicies() throws Exception { String topicName = "java-sns-policy-integ-test-" + System.currentTimeMillis(); topicArn = sns.createTopic(CreateTopicRequest.builder().name(topicName).build()).topicArn(); Policy policy = new Policy() .withStatements(new Statement(Effect.Allow) .withActions(new Action("sns:Subscribe")) .withPrincipals(Principal.ALL_USERS) .withResources(new Resource(topicArn)) .withConditions(new StringCondition(StringComparisonType.StringLike, "sns:Endpoint", "*@amazon.com"), new StringCondition(StringComparisonType.StringEquals, "sns:Protocol", "email"))); sns.setTopicAttributes(SetTopicAttributesRequest.builder() .topicArn(topicArn) .attributeName("Policy") .attributeValue(policy.toJson()) .build()); } }
4,645
0
Create_ds/aws-sdk-java-v2/services/sns/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/sns/src/it/java/software/amazon/awssdk/services/sns/Topics.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.sns; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import software.amazon.awssdk.core.auth.policy.Action; import software.amazon.awssdk.core.auth.policy.Policy; import software.amazon.awssdk.core.auth.policy.Principal; import software.amazon.awssdk.core.auth.policy.Resource; import software.amazon.awssdk.core.auth.policy.Statement; import software.amazon.awssdk.core.auth.policy.Statement.Effect; import software.amazon.awssdk.core.auth.policy.conditions.ConditionFactory; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.services.sns.model.SubscribeRequest; import software.amazon.awssdk.services.sns.model.SubscribeResponse; import software.amazon.awssdk.services.sqs.SqsClient; import software.amazon.awssdk.services.sqs.model.GetQueueAttributesRequest; import software.amazon.awssdk.services.sqs.model.QueueAttributeName; import software.amazon.awssdk.services.sqs.model.SetQueueAttributesRequest; /** * Set of utility methods for working with Amazon SNS topics. */ public class Topics { /** * Subscribes an existing Amazon SQS queue to an existing Amazon SNS topic. * <p> * The specified Amazon SNS client will be used to send the subscription * request, and the Amazon SQS client will be used to modify the policy on * the queue to allow it to receive messages from the SNS topic. * <p> * The policy applied to the SQS queue is similar to this: * <pre> * { * "Version" : "2008-10-17", * "Statement" : [{ * "Sid" : "topic-subscription-arn:aws:sns:us-west-2:599109622955:myTopic", * "Effect" : "Allow", * "Principal" : { * "AWS":["*"] * }, * "Action" : ["sqs:SendMessage"], * "Resource":["arn:aws:sqs:us-west-2:599109622955:myQueue"], * "Condition" : { * "ArnLike":{ * "aws:SourceArn":["arn:aws:sns:us-west-2:599109622955:myTopic"] * } * } * }] * } * </pre> * <p> * <b>IMPORTANT</b>: If there is already an existing policy set for the * specified SQS queue, this operation will overwrite it with a new policy * that allows the SNS topic to deliver messages to the queue. * <p> * <b>IMPORTANT</b>: There might be a small time period immediately after * subscribing the SQS queue to the SNS topic and updating the SQS queue's * policy, where messages are not able to be delivered to the queue. After a * moment, the new queue policy will propagate and the queue will be able to * receive messages. This delay only occurs immediately after initially * subscribing the queue. * <p> * <b>IMPORTANT</b>: The specified queue and topic (as well as the SNS and * SQS client) should both be located in the same AWS region. * * @param sns * The Amazon SNS client to use when subscribing the queue to the * topic. * @param sqs * The Amazon SQS client to use when applying the policy to allow * subscribing to the topic. * @param snsTopicArn * The Amazon Resource Name (ARN) uniquely identifying the Amazon * SNS topic. This value is returned form Amazon SNS when * creating the topic. * @param sqsQueueUrl * The URL uniquely identifying the Amazon SQS queue. This value * is returned from Amazon SQS when creating the queue. * * @return The subscription ARN as returned by Amazon SNS when the queue is * successfully subscribed to the topic. * * @throws SdkClientException * If any internal errors are encountered inside the client * while attempting to make the request or handle the response. * For example if a network connection is not available. * @throws SdkServiceException * If an error response is returned by SnsClient indicating * either a problem with the data in the request, or a server * side issue. */ public static String subscribeQueue(SnsClient sns, SqsClient sqs, String snsTopicArn, String sqsQueueUrl) throws SdkClientException, SdkServiceException { return Topics.subscribeQueue(sns, sqs, snsTopicArn, sqsQueueUrl, false); } /** * Subscribes an existing Amazon SQS queue to an existing Amazon SNS topic. * <p> * The specified Amazon SNS client will be used to send the subscription * request, and the Amazon SQS client will be used to modify the policy on * the queue to allow it to receive messages from the SNS topic. * <p> * The policy applied to the SQS queue is similar to this: * <pre> * { * "Version" : "2008-10-17", * "Statement" : [{ * "Sid" : "topic-subscription-arn:aws:sns:us-west-2:599109622955:myTopic", * "Effect" : "Allow", * "Principal" : { * "AWS":["*"] * }, * "Action" : ["sqs:SendMessage"], * "Resource":["arn:aws:sqs:us-west-2:599109622955:myQueue"], * "Condition" : { * "ArnLike":{ * "aws:SourceArn":["arn:aws:sns:us-west-2:599109622955:myTopic"] * } * } * }] * } * </pre> * <p> * <b>IMPORTANT</b>: There might be a small time period immediately after * subscribing the SQS queue to the SNS topic and updating the SQS queue's * policy, where messages are not able to be delivered to the queue. After a * moment, the new queue policy will propagate and the queue will be able to * receive messages. This delay only occurs immediately after initially * subscribing the queue. * <p> * <b>IMPORTANT</b>: The specified queue and topic (as well as the SNS and * SQS client) should both be located in the same AWS region. * * @param sns * The Amazon SNS client to use when subscribing the queue to the * topic. * @param sqs * The Amazon SQS client to use when applying the policy to allow * subscribing to the topic. * @param snsTopicArn * The Amazon Resource Name (ARN) uniquely identifying the Amazon * SNS topic. This value is returned form Amazon SNS when * creating the topic. * @param sqsQueueUrl * The URL uniquely identifying the Amazon SQS queue. This value * is returned from Amazon SQS when creating the queue. * @param extendPolicy * Decides behavior to overwrite the existing policy or extend it. * * @return The subscription ARN as returned by Amazon SNS when the queue is * successfully subscribed to the topic. * * @throws SdkClientException * If any internal errors are encountered inside the client * while attempting to make the request or handle the response. * For example if a network connection is not available. * @throws SdkServiceException * If an error response is returned by SnsClient indicating * either a problem with the data in the request, or a server * side issue. */ public static String subscribeQueue(SnsClient sns, SqsClient sqs, String snsTopicArn, String sqsQueueUrl, boolean extendPolicy) throws SdkClientException, SdkServiceException { List<String> sqsAttrNames = Arrays.asList(QueueAttributeName.QUEUE_ARN.toString(), QueueAttributeName.POLICY.toString()); Map<String, String> sqsAttrs = sqs.getQueueAttributes(GetQueueAttributesRequest.builder() .queueUrl(sqsQueueUrl) .attributeNamesWithStrings(sqsAttrNames) .build()) .attributesAsStrings(); String sqsQueueArn = sqsAttrs.get(QueueAttributeName.QUEUE_ARN.toString()); String policyJson = sqsAttrs.get(QueueAttributeName.POLICY.toString()); Policy policy = extendPolicy && policyJson != null && policyJson.length() > 0 ? Policy.fromJson(policyJson) : new Policy(); policy.getStatements().add(new Statement(Effect.Allow) .withId("topic-subscription-" + snsTopicArn) .withPrincipals(Principal.ALL_USERS) .withActions(new Action("sqs:SendMessage")) .withResources(new Resource(sqsQueueArn)) .withConditions(ConditionFactory.newSourceArnCondition(snsTopicArn))); Map<String, String> newAttrs = new HashMap<String, String>(); newAttrs.put(QueueAttributeName.POLICY.toString(), policy.toJson()); sqs.setQueueAttributes(SetQueueAttributesRequest.builder().queueUrl(sqsQueueUrl).attributesWithStrings(newAttrs).build()); SubscribeResponse subscribeResult = sns.subscribe(SubscribeRequest.builder() .topicArn(snsTopicArn).protocol("sqs") .endpoint(sqsQueueArn) .build()); return subscribeResult.subscriptionArn(); } }
4,646
0
Create_ds/aws-sdk-java-v2/services/sns/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/sns/src/it/java/software/amazon/awssdk/services/sns/SNSIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.sns; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.net.HttpURLConnection; import java.net.URL; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.junit.After; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.services.sns.model.AddPermissionRequest; import software.amazon.awssdk.services.sns.model.CreateTopicRequest; import software.amazon.awssdk.services.sns.model.CreateTopicResponse; import software.amazon.awssdk.services.sns.model.DeleteTopicRequest; import software.amazon.awssdk.services.sns.model.GetSubscriptionAttributesRequest; import software.amazon.awssdk.services.sns.model.GetTopicAttributesRequest; import software.amazon.awssdk.services.sns.model.GetTopicAttributesResponse; import software.amazon.awssdk.services.sns.model.ListSubscriptionsByTopicRequest; import software.amazon.awssdk.services.sns.model.ListSubscriptionsByTopicResponse; import software.amazon.awssdk.services.sns.model.ListSubscriptionsRequest; import software.amazon.awssdk.services.sns.model.ListSubscriptionsResponse; import software.amazon.awssdk.services.sns.model.ListTopicsRequest; import software.amazon.awssdk.services.sns.model.ListTopicsResponse; import software.amazon.awssdk.services.sns.model.PublishRequest; import software.amazon.awssdk.services.sns.model.RemovePermissionRequest; import software.amazon.awssdk.services.sns.model.SetSubscriptionAttributesRequest; import software.amazon.awssdk.services.sns.model.SetTopicAttributesRequest; import software.amazon.awssdk.services.sns.model.SubscribeRequest; import software.amazon.awssdk.services.sns.model.SubscribeResponse; import software.amazon.awssdk.services.sns.model.Subscription; import software.amazon.awssdk.services.sns.model.UnsubscribeRequest; import software.amazon.awssdk.services.sqs.model.CreateQueueRequest; import software.amazon.awssdk.services.sqs.model.DeleteQueueRequest; import software.amazon.awssdk.services.sqs.model.GetQueueAttributesRequest; import software.amazon.awssdk.services.sqs.model.Message; import software.amazon.awssdk.services.sqs.model.QueueAttributeName; import software.amazon.awssdk.services.sqs.model.ReceiveMessageRequest; import software.amazon.awssdk.services.sqs.model.SetQueueAttributesRequest; /** * Integration tests for Cloudcast operations. */ public class SNSIntegrationTest extends IntegrationTestBase { private static final String DELIVERY_POLICY = "{ " + " \"healthyRetryPolicy\":" + " {" + " \"minDelayTarget\": 1," + " \"maxDelayTarget\": 1," + " \"numRetries\": 1, " + " \"numMaxDelayRetries\": 0, " + " \"backoffFunction\": \"linear\"" + " }" + "}"; private final SignatureChecker signatureChecker = new SignatureChecker(); /** The ARN of the topic created by these tests. */ private String topicArn; /** The URL of the SQS queue created to receive notifications. */ private String queueUrl; private String subscriptionArn; @Before public void setup() { topicArn = null; queueUrl = null; subscriptionArn = null; } /** Releases all resources used by this test. */ @After public void tearDown() throws Exception { if (topicArn != null) { sns.deleteTopic(DeleteTopicRequest.builder().topicArn(topicArn).build()); } if (queueUrl != null) { sqs.deleteQueue(DeleteQueueRequest.builder().queueUrl(queueUrl).build()); } if (subscriptionArn != null) { sns.unsubscribe(UnsubscribeRequest.builder().subscriptionArn(subscriptionArn).build()); } } /** * Tests that we can correctly handle exceptions from SNS. */ @Test public void testCloudcastExceptionHandling() { try { sns.createTopic(CreateTopicRequest.builder().name("").build()); } catch (AwsServiceException exception) { assertEquals("InvalidParameter", exception.awsErrorDetails().errorCode()); assertTrue(exception.getMessage().length() > 5); assertTrue(exception.requestId().length() > 5); assertThat(exception.awsErrorDetails().serviceName()).isEqualTo("Sns"); assertEquals(400, exception.statusCode()); } } @Test public void testSendUnicodeMessages() throws InterruptedException { String unicodeMessage = "你好"; String unicodeSubject = "主题"; topicArn = sns.createTopic(CreateTopicRequest.builder().name("unicodeMessageTest-" + System.currentTimeMillis()).build()) .topicArn(); queueUrl = sqs.createQueue( CreateQueueRequest.builder().queueName("unicodeMessageTest-" + System.currentTimeMillis()).build()) .queueUrl(); subscriptionArn = Topics.subscribeQueue(sns, sqs, topicArn, queueUrl); assertNotNull(subscriptionArn); // Verify that the queue is receiving unicode messages sns.publish(PublishRequest.builder().topicArn(topicArn).message(unicodeMessage).subject(unicodeSubject).build()); String message = receiveMessage(); Map<String, String> messageDetails = parseJSON(message); assertEquals(unicodeMessage, messageDetails.get("Message")); assertEquals(unicodeSubject, messageDetails.get("Subject")); assertNotNull(messageDetails.get("MessageId")); assertNotNull(messageDetails.get("Signature")); sns.deleteTopic(DeleteTopicRequest.builder().topicArn(topicArn).build()); topicArn = null; sqs.deleteQueue(DeleteQueueRequest.builder().queueUrl(queueUrl).build()); queueUrl = null; } /** * Tests that we can invoke operations on Cloudcast and correctly interpret the responses. */ @Test public void testCloudcastOperations() throws Exception { // Create Topic CreateTopicResponse createTopicResult = sns .createTopic(CreateTopicRequest.builder().name("test-topic-" + System.currentTimeMillis()).build()); topicArn = createTopicResult.topicArn(); assertTrue(topicArn.length() > 1); // List Topics Thread.sleep(1000 * 5); ListTopicsResponse listTopicsResult = sns.listTopics(ListTopicsRequest.builder().build()); assertNotNull(listTopicsResult.topics()); assertTopicIsPresent(listTopicsResult.topics(), topicArn); // Set Topic Attributes sns.setTopicAttributes(SetTopicAttributesRequest.builder().topicArn(topicArn).attributeName("DisplayName") .attributeValue("MyTopicName").build()); // Get Topic Attributes GetTopicAttributesResponse getTopicAttributesResult = sns .getTopicAttributes(GetTopicAttributesRequest.builder().topicArn(topicArn).build()); assertEquals("MyTopicName", getTopicAttributesResult.attributes().get("DisplayName")); // Subscribe an SQS queue for notifications String queueArn = initializeReceivingQueue(); SubscribeResponse subscribeResult = sns .subscribe(SubscribeRequest.builder().endpoint(queueArn).protocol("sqs").topicArn(topicArn).build()); subscriptionArn = subscribeResult.subscriptionArn(); assertTrue(subscriptionArn.length() > 1); // List Subscriptions by Topic Thread.sleep(1000 * 5); ListSubscriptionsByTopicResponse listSubscriptionsByTopicResult = sns .listSubscriptionsByTopic(ListSubscriptionsByTopicRequest.builder().topicArn(topicArn).build()); assertSubscriptionIsPresent(listSubscriptionsByTopicResult.subscriptions(), subscriptionArn); // List Subscriptions List<Subscription> subscriptions = getAllSubscriptions(sns); assertSubscriptionIsPresent(subscriptions, subscriptionArn); // Get Subscription Attributes Map<String, String> attributes = sns .getSubscriptionAttributes(GetSubscriptionAttributesRequest.builder().subscriptionArn(subscriptionArn).build()) .attributes(); assertTrue(attributes.size() > 0); Entry<String, String> entry = attributes.entrySet().iterator().next(); assertNotNull(entry.getKey()); assertNotNull(entry.getValue()); // Set Subscription Attributes sns.setSubscriptionAttributes( SetSubscriptionAttributesRequest.builder().subscriptionArn(subscriptionArn).attributeName("DeliveryPolicy") .attributeValue(DELIVERY_POLICY).build()); // Publish sns.publish(PublishRequest.builder().topicArn(topicArn).message("Hello SNS World").subject("Subject").build()); // Receive Published Message String message = receiveMessage(); Map<String, String> messageDetails = parseJSON(message); assertEquals("Hello SNS World", messageDetails.get("Message")); assertEquals("Subject", messageDetails.get("Subject")); assertNotNull(messageDetails.get("MessageId")); assertNotNull(messageDetails.get("Signature")); // Verify Message Signature Certificate certificate = getCertificate(messageDetails.get("SigningCertURL")); assertTrue(signatureChecker.verifyMessageSignature(message, certificate.getPublicKey())); // Add/Remove Permissions sns.addPermission(AddPermissionRequest.builder() .topicArn(topicArn) .label("foo") .actionNames("Publish") .awsAccountIds("750203240092") .build()); Thread.sleep(1000 * 5); sns.removePermission(RemovePermissionRequest.builder().topicArn(topicArn).label("foo").build()); } /** * Get all subscriptions as a list of {@link Subscription} objects * * @param sns * Client * @return List of all subscriptions */ private List<Subscription> getAllSubscriptions(SnsClient sns) { ListSubscriptionsResponse result = sns.listSubscriptions(ListSubscriptionsRequest.builder().build()); List<Subscription> subscriptions = new ArrayList<>(result.subscriptions()); while (result.nextToken() != null) { result = sns.listSubscriptions(ListSubscriptionsRequest.builder().nextToken(result.nextToken()).build()); subscriptions.addAll(result.subscriptions()); } return subscriptions; } @Test public void testSimplifiedMethods() throws InterruptedException { // Create Topic CreateTopicResponse createTopicResult = sns.createTopic(CreateTopicRequest.builder().name("test-topic-" + System.currentTimeMillis()).build()); topicArn = createTopicResult.topicArn(); assertTrue(topicArn.length() > 1); // List Topics Thread.sleep(1000 * 5); ListTopicsResponse listTopicsResult = sns.listTopics(ListTopicsRequest.builder().build()); assertNotNull(listTopicsResult.topics()); assertTopicIsPresent(listTopicsResult.topics(), topicArn); // Set Topic Attributes sns.setTopicAttributes( SetTopicAttributesRequest.builder().topicArn(topicArn).attributeName("DisplayName").attributeValue("MyTopicName") .build()); // Get Topic Attributes GetTopicAttributesResponse getTopicAttributesResult = sns.getTopicAttributes(GetTopicAttributesRequest.builder().topicArn(topicArn).build()); assertEquals("MyTopicName", getTopicAttributesResult.attributes().get("DisplayName")); // Subscribe an SQS queue for notifications queueUrl = sqs.createQueue(CreateQueueRequest.builder().queueName("subscribeTopicTest-" + System.currentTimeMillis()) .build()) .queueUrl(); String queueArn = initializeReceivingQueue(); SubscribeResponse subscribeResult = sns.subscribe(SubscribeRequest.builder().topicArn(topicArn).protocol("sqs").endpoint(queueArn).build()); String subscriptionArn = subscribeResult.subscriptionArn(); assertTrue(subscriptionArn.length() > 1); // List Subscriptions by Topic Thread.sleep(1000 * 5); ListSubscriptionsByTopicResponse listSubscriptionsByTopicResult = sns.listSubscriptionsByTopic(ListSubscriptionsByTopicRequest.builder().topicArn(topicArn).build()); assertSubscriptionIsPresent(listSubscriptionsByTopicResult.subscriptions(), subscriptionArn); // Get Subscription Attributes Map<String, String> attributes = sns.getSubscriptionAttributes(GetSubscriptionAttributesRequest.builder().subscriptionArn(subscriptionArn).build()) .attributes(); assertTrue(attributes.size() > 0); Entry<String, String> entry = attributes.entrySet().iterator().next(); assertNotNull(entry.getKey()); assertNotNull(entry.getValue()); // Set Subscription Attributes sns.setSubscriptionAttributes( SetSubscriptionAttributesRequest.builder().subscriptionArn(subscriptionArn).attributeName("DeliveryPolicy") .attributeValue(DELIVERY_POLICY).build()); // Publish With Subject sns.publish(PublishRequest.builder().topicArn(topicArn).message("Hello SNS World").subject("Subject").build()); // Receive Published Message String message = receiveMessage(); Map<String, String> messageDetails = parseJSON(message); assertEquals("Hello SNS World", messageDetails.get("Message")); assertEquals("Subject", messageDetails.get("Subject")); assertNotNull(messageDetails.get("MessageId")); assertNotNull(messageDetails.get("Signature")); // Publish Without Subject sns.publish(PublishRequest.builder().topicArn(topicArn).message("Hello SNS World").build()); // Receive Published Message message = receiveMessage(); messageDetails = parseJSON(message); assertEquals("Hello SNS World", messageDetails.get("Message")); assertNotNull(messageDetails.get("MessageId")); assertNotNull(messageDetails.get("Signature")); // Add/Remove Permissions sns.addPermission(AddPermissionRequest.builder().topicArn(topicArn).label("foo").awsAccountIds("750203240092") .actionNames("Publish").build()); Thread.sleep(1000 * 5); sns.removePermission(RemovePermissionRequest.builder().topicArn(topicArn).label("foo").build()); // Unsubscribe sns.unsubscribe(UnsubscribeRequest.builder().subscriptionArn(subscriptionArn).build()); // Delete Topic sns.deleteTopic(DeleteTopicRequest.builder().topicArn(topicArn).build()); topicArn = null; } /* * Private Interface */ /** * Polls the SQS queue created earlier in the test until we find our SNS notification message * and returns the base64 decoded message body. */ private String receiveMessage() throws InterruptedException { int maxRetries = 15; while (maxRetries-- > 0) { Thread.sleep(1000 * 10); List<Message> messages = sqs.receiveMessage(ReceiveMessageRequest.builder().queueUrl(queueUrl).build()).messages(); if (messages.size() > 0) { return new String(messages.get(0).body()); } } fail("No SQS messages received after retrying " + maxRetries + "times"); return null; } /** * Creates an SQS queue for this test to use when receiving SNS notifications. We need to use an * SQS queue because otherwise HTTP or email notifications require a confirmation token that is * sent via HTTP or email. Plus an SQS queue lets us test that our notification was delivered. */ private String initializeReceivingQueue() throws InterruptedException { String queueName = "sns-integ-test-" + System.currentTimeMillis(); this.queueUrl = sqs.createQueue(CreateQueueRequest.builder().queueName(queueName).build()).queueUrl(); Thread.sleep(1000 * 4); String queueArn = sqs.getQueueAttributes( GetQueueAttributesRequest.builder().queueUrl(queueUrl).attributeNames(QueueAttributeName.QUEUE_ARN) .build()) .attributes().get(QueueAttributeName.QUEUE_ARN); HashMap<String, String> attributes = new HashMap<>(); attributes.put("Policy", generateSqsPolicyForTopic(queueArn, topicArn)); sqs.setQueueAttributes(SetQueueAttributesRequest.builder().queueUrl(queueUrl).attributesWithStrings(attributes).build()); int policyPropagationDelayInSeconds = 60; System.out.println("Sleeping " + policyPropagationDelayInSeconds + " seconds to let SQS policy propagate"); Thread.sleep(1000 * policyPropagationDelayInSeconds); return queueArn; } /** * Creates a policy to apply to our SQS queue that allows our SNS topic to deliver notifications * to it. Note that this policy is for the SQS queue, *not* for SNS. */ private String generateSqsPolicyForTopic(String queueArn, String topicArn) { String policy = "{ " + " \"Version\":\"2008-10-17\"," + " \"Id\":\"" + queueArn + "/policyId\"," + " \"Statement\": [" + " {" + " \"Sid\":\"" + queueArn + "/statementId\"," + " \"Effect\":\"Allow\"," + " \"Principal\":{\"AWS\":\"*\"}," + " \"Action\":\"SQS:SendMessage\"," + " \"Resource\": \"" + queueArn + "\"," + " \"Condition\":{" + " \"StringEquals\":{\"aws:SourceArn\":\"" + topicArn + "\"}" + " }" + " }" + " ]" + "}"; return policy; } private Certificate getCertificate(String certUrl) { try { return CertificateFactory.getInstance("X509").generateCertificate(getCertificateStream(certUrl)); } catch (CertificateException e) { throw new RuntimeException("Unable to create certificate from " + certUrl, e); } } private InputStream getCertificateStream(String certUrl) { try { URL cert = new URL(certUrl); HttpURLConnection connection = (HttpURLConnection) cert.openConnection(); if (connection.getResponseCode() != 200) { throw new RuntimeException("Received non 200 response when requesting certificate " + certUrl); } return connection.getInputStream(); } catch (IOException e) { throw new UncheckedIOException("Unable to request certificate " + certUrl, e); } } }
4,647
0
Create_ds/aws-sdk-java-v2/services/sns/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/sns/src/it/java/software/amazon/awssdk/services/sns/IntegrationTestBase.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.sns; import static org.junit.Assert.fail; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import java.io.FileNotFoundException; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.BeforeClass; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.model.Subscription; import software.amazon.awssdk.services.sns.model.Topic; import software.amazon.awssdk.services.sqs.SqsClient; import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase; /** * Base class for SNS integration tests; responsible for loading AWS account info for running the * tests, and instantiating clients, etc. */ public abstract class IntegrationTestBase extends AwsIntegrationTestBase { protected static SnsClient sns; protected static SqsClient sqs; /** * Loads the AWS account info for the integration tests and creates SNS and SQS clients for * tests to use. */ @BeforeClass public static void setUp() throws FileNotFoundException, IOException { sns = SnsClient.builder() .credentialsProvider(StaticCredentialsProvider.create(getCredentials())) .region(Region.US_WEST_2) .build(); sqs = SqsClient.builder() .credentialsProvider(StaticCredentialsProvider.create(getCredentials())) .region(Region.US_WEST_2) .build(); } /** * Asserts that the list of topics contains one with the specified ARN, otherwise fails the * current test. */ protected void assertTopicIsPresent(List<Topic> topics, String topicArn) { for (Topic topic : topics) { if (topic.topicArn().equals(topicArn)) { return; } } fail("Topic '" + topicArn + "' was not present in specified list of topics."); } /** * Asserts that the list of subscriptions contains one with the specified ARN, otherwise fails * the current test. */ protected void assertSubscriptionIsPresent(List<Subscription> subscriptions, String subscriptionArn) { for (Subscription subscription : subscriptions) { if (subscription.subscriptionArn().equals(subscriptionArn)) { return; } } fail("Subscription '" + subscriptionArn + "' was not present in specified list of subscriptions."); } /** * Turns a one level deep JSON string into a Map. */ protected Map<String, String> parseJSON(String jsonmessage) { Map<String, String> parsed = new HashMap<String, String>(); JsonFactory jf = new JsonFactory(); try { JsonParser parser = jf.createJsonParser(jsonmessage); parser.nextToken(); // shift past the START_OBJECT that begins the JSON while (parser.nextToken() != JsonToken.END_OBJECT) { String fieldname = parser.getCurrentName(); parser.nextToken(); // move to value, or START_OBJECT/START_ARRAY String value = parser.getText(); parsed.put(fieldname, value); } } catch (JsonParseException e) { // JSON could not be parsed e.printStackTrace(); } catch (IOException e) { // Rare exception } return parsed; } }
4,648
0
Create_ds/aws-sdk-java-v2/services/sns/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/sns/src/it/java/software/amazon/awssdk/services/sns/SignatureChecker.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.sns; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import java.io.IOException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.Signature; import java.security.SignatureException; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import software.amazon.awssdk.utils.BinaryUtils; /** * Utility for validating signatures on a Simple Notification Service JSON message. */ public class SignatureChecker { private static final String NOTIFICATION_TYPE = "Notification"; private static final String SUBSCRIBE_TYPE = "SubscriptionConfirmation"; private static final String UNSUBSCRIBE_TYPE = "UnsubscribeConfirmation"; private static final String TYPE = "Type"; private static final String SUBSCRIBE_URL = "SubscribeURL"; private static final String MESSAGE = "Message"; private static final String TIMESTAMP = "Timestamp"; private static final String SIGNATURE_VERSION = "SignatureVersion"; private static final String SIGNATURE = "Signature"; private static final String MESSAGE_ID = "MessageId"; private static final String SUBJECT = "Subject"; private static final String TOPIC = "TopicArn"; private static final String TOKEN = "Token"; private static final Set<String> INTERESTING_FIELDS = new HashSet<>(Arrays.asList(TYPE, SUBSCRIBE_URL, MESSAGE, TIMESTAMP, SIGNATURE, SIGNATURE_VERSION, MESSAGE_ID, SUBJECT, TOPIC, TOKEN)); private Signature sigChecker; /** * Validates the signature on a Simple Notification Service message. No * Amazon-specific dependencies, just plain Java crypto and Jackson for * parsing * * @param message * A JSON-encoded Simple Notification Service message. Note: the * JSON may be only one level deep. * @param publicKey * The Simple Notification Service public key, exactly as you'd * see it when retrieved from the cert. * * @return True if the message was correctly validated, otherwise false. */ public boolean verifyMessageSignature(String message, PublicKey publicKey) { // extract the type and signature parameters Map<String, String> parsed = parseJson(message); return verifySignature(parsed, publicKey); } /** * Validates the signature on a Simple Notification Service message. No * Amazon-specific dependencies, just plain Java crypto * * @param parsedMessage * A map of Simple Notification Service message. * @param publicKey * The Simple Notification Service public key, exactly as you'd * see it when retrieved from the cert. * * @return True if the message was correctly validated, otherwise false. */ public boolean verifySignature(Map<String, String> parsedMessage, PublicKey publicKey) { boolean valid = false; String version = parsedMessage.get(SIGNATURE_VERSION); if (version.equals("1")) { // construct the canonical signed string String type = parsedMessage.get(TYPE); String signature = parsedMessage.get(SIGNATURE); String signed = ""; if (type.equals(NOTIFICATION_TYPE)) { signed = stringToSign(publishMessageValues(parsedMessage)); } else if (type.equals(SUBSCRIBE_TYPE)) { signed = stringToSign(subscribeMessageValues(parsedMessage)); } else if (type.equals(UNSUBSCRIBE_TYPE)) { signed = stringToSign(subscribeMessageValues(parsedMessage)); // no difference, for now } else { throw new RuntimeException("Cannot process message of type " + type); } valid = verifySignature(signed, signature, publicKey); } return valid; } /** * Does the actual Java cryptographic verification of the signature. This * method does no handling of the many rare exceptions it is required to * catch. * * This can also be used to verify the signature from the x-amz-sns-signature http header * * @param message * Exact string that was signed. In the case of the x-amz-sns-signature header the * signing string is the entire post body * @param signature * Base64-encoded signature of the message */ public boolean verifySignature(String message, String signature, PublicKey publicKey) { boolean result = false; byte[] sigbytes = null; try { sigbytes = BinaryUtils.fromBase64Bytes(signature.getBytes()); sigChecker = Signature.getInstance("SHA1withRSA"); //check the signature sigChecker.initVerify(publicKey); sigChecker.update(message.getBytes()); result = sigChecker.verify(sigbytes); } catch (NoSuchAlgorithmException e) { // Rare exception: JVM does not support SHA1 with RSA } catch (InvalidKeyException e) { // Rare exception: The private key was incorrectly formatted } catch (SignatureException e) { // Rare exception: Catch-all exception for the signature checker } return result; } protected String stringToSign(SortedMap<String, String> signables) { // each key and value is followed by a newline StringBuilder sb = new StringBuilder(); for (String k : signables.keySet()) { sb.append(k).append("\n"); sb.append(signables.get(k)).append("\n"); } String result = sb.toString(); return result; } private Map<String, String> parseJson(String jsonmessage) { Map<String, String> parsed = new HashMap<String, String>(); JsonFactory jf = new JsonFactory(); try { JsonParser parser = jf.createParser(jsonmessage); parser.nextToken(); //shift past the START_OBJECT that begins the JSON while (parser.nextToken() != JsonToken.END_OBJECT) { String fieldname = parser.getCurrentName(); if (!INTERESTING_FIELDS.contains(fieldname)) { parser.skipChildren(); continue; } parser.nextToken(); // move to value, or START_OBJECT/START_ARRAY String value; if (parser.getCurrentToken() == JsonToken.START_ARRAY) { value = ""; boolean first = true; while (parser.nextToken() != JsonToken.END_ARRAY) { if (!first) { value += ","; } first = false; value += parser.getText(); } } else { value = parser.getText(); } parsed.put(fieldname, value); } } catch (JsonParseException e) { // JSON could not be parsed e.printStackTrace(); } catch (IOException e) { // Rare exception } return parsed; } private TreeMap<String, String> publishMessageValues(Map<String, String> parsedMessage) { TreeMap<String, String> signables = new TreeMap<String, String>(); String[] keys = {MESSAGE, MESSAGE_ID, SUBJECT, TYPE, TIMESTAMP, TOPIC}; for (String key : keys) { if (parsedMessage.containsKey(key)) { signables.put(key, parsedMessage.get(key)); } } return signables; } private TreeMap<String, String> subscribeMessageValues(Map<String, String> parsedMessage) { TreeMap<String, String> signables = new TreeMap<String, String>(); String[] keys = {SUBSCRIBE_URL, MESSAGE, MESSAGE_ID, TYPE, TIMESTAMP, TOKEN, TOPIC}; for (String key : keys) { if (parsedMessage.containsKey(key)) { signables.put(key, parsedMessage.get(key)); } } return signables; } }
4,649
0
Create_ds/aws-sdk-java-v2/services/sns/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/sns/src/it/java/software/amazon/awssdk/services/sns/SessionBasedAuthenticationIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.sns; import org.junit.Test; import software.amazon.awssdk.testutils.service.AwsTestBase; /** * Simple smoke test for session management. */ public class SessionBasedAuthenticationIntegrationTest extends AwsTestBase { /** * TODO: reenable */ @Test public void testSessions() throws Exception { setUpCredentials(); // RenewableAWSSessionCredentials sessionCredentials = new // STSSessionCredentials(credentials); // AmazonSnsClient sns = new AmazonSnsClient(sessionCredentials); // // sns.createTopic(new CreateTopicRequest().withName("java" + // this.getClass().getSimpleName() // + System.currentTimeMillis())); } }
4,650
0
Create_ds/aws-sdk-java-v2/services/cloudhsm/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/cloudhsm/src/it/java/software/amazon/awssdk/services/cloudhsm/IntegrationTestBase.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.cloudhsm; import org.junit.BeforeClass; import software.amazon.awssdk.testutils.service.AwsTestBase; public class IntegrationTestBase extends AwsTestBase { protected static CloudHsmClient client; @BeforeClass public static void setup() throws Exception { setUpCredentials(); client = CloudHsmClient.builder().credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build(); } }
4,651
0
Create_ds/aws-sdk-java-v2/services/inspector/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/inspector/src/test/java/software/amazon/awssdk/services/inspector/InspectorErrorUnmarshallingTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.inspector;/* * Copyright 2011-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static org.junit.Assert.assertEquals; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.net.URI; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.inspector.model.AccessDeniedException; import software.amazon.awssdk.services.inspector.model.ListRulesPackagesRequest; public class InspectorErrorUnmarshallingTest { @Rule public WireMockRule wireMock = new WireMockRule(0); private InspectorClient inspector; @Before public void setup() { StaticCredentialsProvider credsProvider = StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid")); inspector = InspectorClient.builder() .credentialsProvider(credsProvider) .region(Region.US_EAST_1) .endpointOverride(URI.create("http://localhost:" + wireMock.port())) .build(); } /** * Some error shapes in Inspector define an errorCode member which clashes with the errorCode * defined in {@link SdkServiceException}. We've customized the name of the * modeled error code so both can be used by customers. This test asserts that both are * unmarshalled correctly. */ @Test public void errorCodeAndInspectorErrorCodeUnmarshalledCorrectly() { stubFor(post(urlEqualTo("/")).willReturn(aResponse().withStatus(400).withBody( "{\"__type\":\"AccessDeniedException\",\"errorCode\": \"ACCESS_DENIED_TO_RULES_PACKAGE\", " + "\"Message\":\"User: arn:aws:iam::1234:user/no-perms is not authorized to perform: inspector:ListRulesPackages\"}"))); try { inspector.listRulesPackages(ListRulesPackagesRequest.builder().build()); } catch (AccessDeniedException e) { assertEquals("AccessDeniedException", e.awsErrorDetails().errorCode()); assertEquals("ACCESS_DENIED_TO_RULES_PACKAGE", e.inspectorErrorCodeAsString()); } } }
4,652
0
Create_ds/aws-sdk-java-v2/services/s3control/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/s3control/src/test/java/software/amazon/awssdk/services/s3control/EndpointResolutionTest.java
package software.amazon.awssdk.services.s3control; import org.junit.Test; import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; import software.amazon.awssdk.regions.Region; public class EndpointResolutionTest { @Test(expected = IllegalStateException.class) public void duplicateDualstackSettings_throwsException() { S3ControlClient.builder() .region(Region.US_WEST_2) .credentialsProvider(AnonymousCredentialsProvider.create()) .dualstackEnabled(true) .serviceConfiguration(c -> c.dualstackEnabled(true)) .build(); } }
4,653
0
Create_ds/aws-sdk-java-v2/services/s3control/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/s3control/src/test/java/software/amazon/awssdk/services/s3control/BuilderClientContextParamsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3control; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.ArgumentCaptor; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute; import software.amazon.awssdk.services.s3control.endpoints.S3ControlClientContextParams; import software.amazon.awssdk.services.s3control.model.ListJobsRequest; import software.amazon.awssdk.utils.AttributeMap; public class BuilderClientContextParamsTest { private ExecutionInterceptor mockInterceptor; private static AttributeMap baseExpectedParams; @BeforeAll public static void setup() { // This is the set of client context params with their values the same as default values in S3ControlConfiguration baseExpectedParams = AttributeMap.builder() .put(S3ControlClientContextParams.USE_ARN_REGION, false) .build(); } @BeforeEach public void methodSetup() { mockInterceptor = mock(ExecutionInterceptor.class); when(mockInterceptor.modifyRequest(any(), any())).thenThrow(new RuntimeException("Oops")); } @MethodSource("testCases") @ParameterizedTest public void verifyParams(TestCase tc) { S3ControlClientBuilder builder = S3ControlClient.builder() .overrideConfiguration(o -> o.addExecutionInterceptor(mockInterceptor)); if (tc.config() != null) { builder.serviceConfiguration(tc.config()); } if (tc.builderModifier() != null) { tc.builderModifier().accept(builder); } if (tc.exception != null) { assertThatThrownBy(builder::build) .isInstanceOf(tc.exception) .hasMessageContaining(tc.exceptionMessage); } else { assertThatThrownBy(() -> { S3ControlClient s3control = builder.build(); s3control.listJobs(ListJobsRequest.builder().accountId("1234").build()); }).hasMessageContaining("Oops"); ArgumentCaptor<ExecutionAttributes> executionAttrsCaptor = ArgumentCaptor.forClass(ExecutionAttributes.class); verify(mockInterceptor).modifyRequest(any(), executionAttrsCaptor.capture()); AttributeMap clientContextParams = executionAttrsCaptor.getValue().getAttribute(SdkInternalExecutionAttribute.CLIENT_CONTEXT_PARAMS); assertThat(clientContextParams).isEqualTo(tc.expectedParams().merge(baseExpectedParams)); } } public static List<TestCase> testCases() { List<TestCase> testCases = new ArrayList<>(); // UseArnRegion on config testCases.add( TestCase.builder() .config(S3ControlConfiguration.builder() .useArnRegionEnabled(true) .build()) .expectedParams(AttributeMap.builder() .put(S3ControlClientContextParams.USE_ARN_REGION, true) .build()) .build() ); // UseArnRegion on builder testCases.add( TestCase.builder() .builderModifier(b -> b.useArnRegion(true)) .expectedParams(AttributeMap.builder() .put(S3ControlClientContextParams.USE_ARN_REGION, true) .build()) .build() ); // UseArnRegion on config and builder testCases.add( TestCase.builder() .config(S3ControlConfiguration.builder() .useArnRegionEnabled(true) .build()) .builderModifier(b -> b.useArnRegion(true)) .exception(IllegalStateException.class) .exceptionMessage("UseArnRegion") .build() ); return testCases; } public static class TestCase { private final S3ControlConfiguration config; private final Consumer<S3ControlClientBuilder> builderModifier; private final Class<?> exception; private final String exceptionMessage; private final AttributeMap expectedParams; private TestCase(Builder b) { this.config = b.config; this.builderModifier = b.builderModifier; this.exception = b.exception; this.exceptionMessage = b.exceptionMessage; this.expectedParams = b.expectedParams; } public S3ControlConfiguration config() { return config; } public Consumer<S3ControlClientBuilder> builderModifier() { return builderModifier; } public Class<?> exception() { return exception; } public String exceptionMessage() { return exceptionMessage; } public AttributeMap expectedParams() { return expectedParams; } public static Builder builder() { return new Builder(); } public static class Builder { private S3ControlConfiguration config; private Consumer<S3ControlClientBuilder> builderModifier; private Class<?> exception; private String exceptionMessage; private AttributeMap expectedParams; public Builder config(S3ControlConfiguration config) { this.config = config; return this; } public Builder builderModifier(Consumer<S3ControlClientBuilder> builderModifier) { this.builderModifier = builderModifier; return this; } public Builder exception(Class<?> exception) { this.exception = exception; return this; } public Builder exceptionMessage(String exceptionMessage) { this.exceptionMessage = exceptionMessage; return this; } private Builder expectedParams(AttributeMap expectedParams) { this.expectedParams = expectedParams; return this; } public TestCase build() { return new TestCase(this); } } } }
4,654
0
Create_ds/aws-sdk-java-v2/services/s3control/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/s3control/src/test/java/software/amazon/awssdk/services/s3control/EndpointOverrideEndpointResolutionTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3control; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.function.Consumer; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute; import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.signer.Presigner; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.http.AbortableInputStream; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3control.model.CreateBucketRequest; import software.amazon.awssdk.services.s3control.model.GetAccessPointRequest; import software.amazon.awssdk.services.s3control.model.GetBucketRequest; import software.amazon.awssdk.testutils.service.http.MockSyncHttpClient; import software.amazon.awssdk.utils.StringInputStream; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; @RunWith(Parameterized.class) public class EndpointOverrideEndpointResolutionTest { private final TestCase testCase; private final SignerAndPresigner mockSigner; private final MockSyncHttpClient mockHttpClient; private final S3ControlClient s3ControlClient; public interface SignerAndPresigner extends Signer, Presigner {} public EndpointOverrideEndpointResolutionTest(TestCase testCase) { this.testCase = testCase; this.mockSigner = Mockito.mock(SignerAndPresigner.class); this.mockHttpClient = new MockSyncHttpClient(); this.s3ControlClient = S3ControlClient.builder() .region(testCase.clientRegion) .credentialsProvider(StaticCredentialsProvider.create( AwsBasicCredentials.create("dummy-key", "dummy-secret"))) .endpointOverride(testCase.endpointUrl) .serviceConfiguration(testCase.s3ControlConfiguration) .httpClient(mockHttpClient) .dualstackEnabled(testCase.clientDualstackEnabled) .overrideConfiguration(c -> c.putAdvancedOption(SdkAdvancedClientOption.SIGNER, mockSigner)) .build(); HttpExecuteResponse response = HttpExecuteResponse.builder() .response(SdkHttpResponse.builder().statusCode(200).build()) .responseBody(AbortableInputStream.create(new StringInputStream("<body/>"))) .build(); mockHttpClient.stubNextResponse(response); Mockito.when(mockSigner.sign(any(), any())).thenAnswer(r -> r.getArgument(0, SdkHttpFullRequest.class)); Mockito.when(mockSigner.presign(any(), any())).thenAnswer(r -> r.getArgument(0, SdkHttpFullRequest.class) .copy(h -> h.putRawQueryParameter("X-Amz-SignedHeaders", "host"))); } @Test public void s3ControlClient_endpointSigningRegionAndServiceNamesAreCorrect() { try { if (testCase.getAccessPointRequest != null) { s3ControlClient.getAccessPoint(testCase.getAccessPointRequest); } else if (testCase.createBucketRequest != null) { s3ControlClient.createBucket(testCase.createBucketRequest); } else { s3ControlClient.getBucket(testCase.getBucketRequest); } assertThat(testCase.expectedException).isNull(); assertThat(mockHttpClient.getLastRequest().getUri()).isEqualTo(testCase.expectedEndpoint); assertThat(signingRegion()).isEqualTo(testCase.expectedSigningRegion); assertThat(signingServiceName()).isEqualTo(testCase.expectedSigningServiceName); } catch (RuntimeException e) { if (testCase.expectedException == null) { throw e; } assertThat(e).isInstanceOf(testCase.expectedException); } } private String signingServiceName() { return attributesPassedToSigner().getAttribute(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME); } private Region signingRegion() { return attributesPassedToSigner().getAttribute(AwsSignerExecutionAttribute.SIGNING_REGION); } private ExecutionAttributes attributesPassedToSigner() { ArgumentCaptor<ExecutionAttributes> executionAttributes = ArgumentCaptor.forClass(ExecutionAttributes.class); Mockito.verify(mockSigner, Mockito.atLeast(0)).sign(any(), executionAttributes.capture()); if (executionAttributes.getAllValues().isEmpty()) { return attributesPassedToPresigner(); } return executionAttributes.getValue(); } private ExecutionAttributes attributesPassedToPresigner() { ArgumentCaptor<ExecutionAttributes> executionAttributes = ArgumentCaptor.forClass(ExecutionAttributes.class); Mockito.verify(mockSigner).presign(any(), executionAttributes.capture()); return executionAttributes.getValue(); } @Parameterized.Parameters(name = "{0}") public static Collection<TestCase> testCases() { List<TestCase> cases = new ArrayList<>(); cases.add(new TestCase().setCaseName("get-access-point by access point name") .setGetAccessPointRequest(r -> r.name("apname").accountId("123456789012")) .setEndpointUrl("https://beta.example.com") .setClientRegion(Region.US_WEST_2) .setExpectedEndpoint("https://123456789012.beta.example.com/v20180820/accesspoint/apname") .setExpectedSigningServiceName("s3") .setExpectedSigningRegion(Region.US_WEST_2)); cases.add(new TestCase().setCaseName("get-access-point by access point name with http, path, query and port") .setGetAccessPointRequest(r -> r.name("apname").accountId("123456789012")) .setEndpointUrl("http://beta.example.com:1234/path?foo=bar") .setClientRegion(Region.US_WEST_2) .setExpectedEndpoint("http://123456789012.beta.example.com:1234/path/v20180820/accesspoint/apname?foo=bar") .setExpectedSigningServiceName("s3") .setExpectedSigningRegion(Region.US_WEST_2)); cases.add(new TestCase().setCaseName("get-access-point by outpost access point arn") .setGetAccessPointRequest(r -> r.name("arn:aws:s3-outposts:us-west-2:123456789012:outpost:op-01234567890123456:accesspoint:myaccesspoint")) .setEndpointUrl("https://beta.example.com") .setClientRegion(Region.US_WEST_2) .setExpectedEndpoint("https://beta.example.com/v20180820/accesspoint/arn%3Aaws%3As3-outposts%3Aus-west-2%3A123456789012%3Aoutpost%3Aop-01234567890123456%3Aaccesspoint%3Amyaccesspoint") .setExpectedSigningServiceName("s3-outposts") .setExpectedSigningRegion(Region.US_WEST_2)); cases.add(new TestCase().setCaseName("get-access-point by outpost access point arn with http, path, query and port") .setGetAccessPointRequest(r -> r.name("arn:aws:s3-outposts:us-west-2:123456789012:outpost:op-01234567890123456:accesspoint:myaccesspoint")) .setEndpointUrl("http://beta.example.com:1234/path?foo=bar") .setClientRegion(Region.US_WEST_2) .setExpectedEndpoint("http://beta.example.com:1234/path/v20180820/accesspoint/arn%3Aaws%3As3-outposts%3Aus-west-2%3A123456789012%3Aoutpost%3Aop-01234567890123456%3Aaccesspoint%3Amyaccesspoint?foo=bar") .setExpectedSigningServiceName("s3-outposts") .setExpectedSigningRegion(Region.US_WEST_2)); cases.add(new TestCase().setCaseName("create-bucket with outpost ID") .setCreateBucketRequest(r -> r.bucket("bucketname").outpostId("op-123")) .setEndpointUrl("https://beta.example.com") .setClientRegion(Region.US_WEST_2) .setExpectedEndpoint("https://beta.example.com/v20180820/bucket/bucketname") .setExpectedSigningServiceName("s3-outposts") .setExpectedSigningRegion(Region.US_WEST_2)); cases.add(new TestCase().setCaseName("create-bucket with outpost ID, http, path, query and port") .setCreateBucketRequest(r -> r.bucket("bucketname").outpostId("op-123")) .setEndpointUrl("http://beta.example.com:1234/path?foo=bar") .setClientRegion(Region.US_WEST_2) .setExpectedEndpoint("http://beta.example.com:1234/path/v20180820/bucket/bucketname?foo=bar") .setExpectedSigningServiceName("s3-outposts") .setExpectedSigningRegion(Region.US_WEST_2)); cases.add(new TestCase().setCaseName("get-bucket with outpost bucket arn") .setGetBucketRequest(r -> r.bucket("arn:aws:s3-outposts:us-west-2:123456789012:outpost:op-01234567890123456:bucket:mybucket")) .setEndpointUrl("https://beta.example.com") .setClientRegion(Region.US_WEST_2) .setExpectedEndpoint("https://beta.example.com/v20180820/bucket/arn%3Aaws%3As3-outposts%3Aus-west-2%3A123456789012%3Aoutpost%3Aop-01234567890123456%3Abucket%3Amybucket") .setExpectedSigningServiceName("s3-outposts") .setExpectedSigningRegion(Region.US_WEST_2)); cases.add(new TestCase().setCaseName("get-bucket with outpost bucket arn, http, path, query and port") .setGetBucketRequest(r -> r.bucket("arn:aws:s3-outposts:us-west-2:123456789012:outpost:op-01234567890123456:bucket:mybucket")) .setEndpointUrl("http://beta.example.com:1234/path?foo=bar") .setClientRegion(Region.US_WEST_2) .setExpectedEndpoint("http://beta.example.com:1234/path/v20180820/bucket/arn%3Aaws%3As3-outposts%3Aus-west-2%3A123456789012%3Aoutpost%3Aop-01234567890123456%3Abucket%3Amybucket?foo=bar") .setExpectedSigningServiceName("s3-outposts") .setExpectedSigningRegion(Region.US_WEST_2)); cases.add(new TestCase().setCaseName("get-access-point by access point name with dualstack via service config") .setGetAccessPointRequest(r -> r.name("apname").accountId("123456789012")) .setEndpointUrl("https://beta.example.com") .setS3ControlConfiguration(c -> c.dualstackEnabled(true)) .setClientRegion(Region.US_WEST_2) .setExpectedException(SdkClientException.class)); cases.add(new TestCase().setCaseName("get-access-point by access point name with dualstack via client builder") .setGetAccessPointRequest(r -> r.name("apname").accountId("123456789012")) .setEndpointUrl("https://beta.example.com") .setClientDualstackEnabled(true) .setClientRegion(Region.US_WEST_2) .setExpectedException(SdkClientException.class)); cases.add(new TestCase().setCaseName("get-access-point by outpost access point arn with dualstack") .setGetAccessPointRequest(r -> r.name("arn:aws:s3-outposts:us-west-2:123456789012:outpost:op-01234567890123456:accesspoint:myaccesspoint")) .setEndpointUrl("https://beta.example.com") .setS3ControlConfiguration(c -> c.dualstackEnabled(true)) .setClientRegion(Region.US_WEST_2) .setExpectedException(SdkClientException.class)); cases.add(new TestCase().setCaseName("create-bucket with outpost ID with dualstack") .setCreateBucketRequest(r -> r.bucket("bucketname").outpostId("op-123")) .setEndpointUrl("https://beta.example.com") .setS3ControlConfiguration(c -> c.dualstackEnabled(true)) .setClientRegion(Region.US_WEST_2) .setExpectedException(SdkClientException.class)); cases.add(new TestCase().setCaseName("get-bucket with outpost bucket arn with dualstack") .setGetBucketRequest(r -> r.bucket("arn:aws:s3-outposts:us-west-2:123456789012:outpost:op-01234567890123456:bucket:mybucket")) .setEndpointUrl("https://beta.example.com") .setS3ControlConfiguration(c -> c.dualstackEnabled(true)) .setClientRegion(Region.US_WEST_2) .setExpectedException(SdkClientException.class)); return cases; } private static class TestCase { private String caseName; private URI endpointUrl; private GetAccessPointRequest getAccessPointRequest; private CreateBucketRequest createBucketRequest; private GetBucketRequest getBucketRequest; private S3ControlConfiguration s3ControlConfiguration = S3ControlConfiguration.builder().build(); private Region clientRegion; private URI expectedEndpoint; private String expectedSigningServiceName; private Region expectedSigningRegion; private Class<? extends RuntimeException> expectedException; private Boolean clientDualstackEnabled; public TestCase setCaseName(String caseName) { this.caseName = caseName; return this; } public TestCase setGetAccessPointRequest(Consumer<GetAccessPointRequest.Builder> consumer) { GetAccessPointRequest.Builder builder = GetAccessPointRequest.builder(); consumer.accept(builder); this.getAccessPointRequest = builder.build(); return this; } public TestCase setCreateBucketRequest(Consumer<CreateBucketRequest.Builder> consumer) { CreateBucketRequest.Builder builder = CreateBucketRequest.builder(); consumer.accept(builder); this.createBucketRequest = builder.build(); return this; } public TestCase setGetBucketRequest(Consumer<GetBucketRequest.Builder> consumer) { GetBucketRequest.Builder builder = GetBucketRequest.builder(); consumer.accept(builder); this.getBucketRequest = builder.build(); return this; } public TestCase setEndpointUrl(String endpointUrl) { this.endpointUrl = URI.create(endpointUrl); return this; } public TestCase setS3ControlConfiguration(Consumer<S3ControlConfiguration.Builder> s3ControlConfiguration) { S3ControlConfiguration.Builder configBuilder = S3ControlConfiguration.builder(); s3ControlConfiguration.accept(configBuilder); this.s3ControlConfiguration = configBuilder.build(); return this; } public TestCase setClientRegion(Region clientRegion) { this.clientRegion = clientRegion; return this; } public TestCase setClientDualstackEnabled(Boolean clientDualstackEnabled) { this.clientDualstackEnabled = clientDualstackEnabled; return this; } public TestCase setExpectedEndpoint(String expectedEndpoint) { this.expectedEndpoint = URI.create(expectedEndpoint); return this; } public TestCase setExpectedSigningServiceName(String expectedSigningServiceName) { this.expectedSigningServiceName = expectedSigningServiceName; return this; } public TestCase setExpectedSigningRegion(Region expectedSigningRegion) { this.expectedSigningRegion = expectedSigningRegion; return this; } public TestCase setExpectedException(Class<? extends RuntimeException> expectedException) { this.expectedException = expectedException; return this; } @Override public String toString() { return this.caseName; } } }
4,655
0
Create_ds/aws-sdk-java-v2/services/s3control/src/test/java/software/amazon/awssdk/services/s3control
Create_ds/aws-sdk-java-v2/services/s3control/src/test/java/software/amazon/awssdk/services/s3control/internal/S3ControlWireMockTest.java
/* * Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3control.internal; import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.github.tomakehurst.wiremock.core.WireMockConfiguration; import com.github.tomakehurst.wiremock.junit.WireMockRule; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3control.S3ControlClient; import software.amazon.awssdk.utils.builder.SdkBuilder; public class S3ControlWireMockTest { @Rule public WireMockRule mockServer = new WireMockRule(new WireMockConfiguration().port(0).httpsPort(0)); private S3ControlClient client; @Before public void setup() { client = S3ControlClient.builder() .region(Region.US_WEST_2) .credentialsProvider(() -> AwsBasicCredentials.create("test", "test")) .build(); } @Test public void invalidAccountId_shouldThrowException() { assertThatThrownBy(() -> client.getPublicAccessBlock(b -> b.accountId("1234#"))) .isInstanceOf(SdkClientException.class) .hasMessageContaining("AccountId must only contain a-z, A-Z, 0-9 and `-`."); } @Test public void nullAccountId_shouldThrowException() { assertThatThrownBy(() -> client.getPublicAccessBlock(SdkBuilder::build)) .isInstanceOf(SdkClientException.class) .hasMessageContaining("AccountId is required but not set"); } }
4,656
0
Create_ds/aws-sdk-java-v2/services/s3control/src/test/java/software/amazon/awssdk/services/s3control
Create_ds/aws-sdk-java-v2/services/s3control/src/test/java/software/amazon/awssdk/services/s3control/internal/S3ControlArnConverterTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3control.internal; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import java.util.Optional; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import software.amazon.awssdk.arns.Arn; import software.amazon.awssdk.services.s3.internal.resource.S3AccessPointResource; import software.amazon.awssdk.services.s3.internal.resource.S3OutpostResource; import software.amazon.awssdk.services.s3.internal.resource.S3Resource; import software.amazon.awssdk.services.s3control.S3ControlBucketResource; public class S3ControlArnConverterTest { private static final S3ControlArnConverter ARN_PARSER = S3ControlArnConverter.getInstance(); @Rule public ExpectedException exception = ExpectedException.none(); @Test public void parseArn_outpostBucketArn() { S3Resource resource = ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("outpost/1234/bucket/myBucket") .build()); assertThat(resource, instanceOf(S3ControlBucketResource.class)); S3ControlBucketResource bucketResource = (S3ControlBucketResource) resource; assertThat(bucketResource.bucketName(), is("myBucket")); assertThat(bucketResource.parentS3Resource().get(), instanceOf(S3OutpostResource.class)); S3OutpostResource outpostResource = (S3OutpostResource) bucketResource.parentS3Resource().get(); assertThat(outpostResource.accountId(), is(Optional.of("123456789012"))); assertThat(outpostResource.partition(), is(Optional.of("aws"))); assertThat(outpostResource.region(), is(Optional.of("us-east-1"))); assertThat(outpostResource.type(), is(S3ControlResourceType.OUTPOST.toString())); assertThat(outpostResource.outpostId(), is("1234")); } @Test public void parseArn_outpostAccessPointArn() { S3Resource resource = ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3-outposts") .region("us-east-1") .accountId("123456789012") .resource("outpost/1234/accesspoint/myAccessPoint") .build()); assertThat(resource, instanceOf(S3AccessPointResource.class)); S3AccessPointResource accessPointResource = (S3AccessPointResource) resource; assertThat(accessPointResource.accessPointName(), is("myAccessPoint")); assertThat(accessPointResource.parentS3Resource().get(), instanceOf(S3OutpostResource.class)); S3OutpostResource outpostResource = (S3OutpostResource) accessPointResource.parentS3Resource().get(); assertThat(outpostResource.outpostId(), is("1234")); assertThat(outpostResource.accountId(), is(Optional.of("123456789012"))); assertThat(outpostResource.partition(), is(Optional.of("aws"))); assertThat(outpostResource.region(), is(Optional.of("us-east-1"))); } @Test public void parseArn_invalidOutpostAccessPointMissingAccessPointName_shouldThrowException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("Invalid format"); ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("outpost:op-01234567890123456:accesspoint") .build()); } @Test public void parseArn_invalidOutpostAccessPointMissingOutpostId_shouldThrowException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("Invalid format"); ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("outpost/myaccesspoint") .build()); } @Test public void parseArn_malformedOutpostArn_shouldThrowException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("Unknown outpost ARN"); ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("outpost:1:accesspoin1:1") .build()); } @Test public void parseArn_unknownResource() { exception.expect(IllegalArgumentException.class); exception.expectMessage("ARN type"); ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("unknown:foobar") .build()); } @Test public void parseArn_unknownType_throwsCorrectException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("invalidType"); ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("invalidType:something") .build()); } }
4,657
0
Create_ds/aws-sdk-java-v2/services/s3control/src/test/java/software/amazon/awssdk/services/s3control
Create_ds/aws-sdk-java-v2/services/s3control/src/test/java/software/amazon/awssdk/services/s3control/internal/S3ControlBucketResourceTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3control.internal; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import java.util.Optional; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import software.amazon.awssdk.services.s3.internal.resource.S3BucketResource; import software.amazon.awssdk.services.s3.internal.resource.S3OutpostResource; import software.amazon.awssdk.services.s3control.S3ControlBucketResource; public class S3ControlBucketResourceTest { @Rule public ExpectedException exception = ExpectedException.none(); @Test public void buildWithAllPropertiesSet() { S3ControlBucketResource bucketResource = S3ControlBucketResource.builder() .bucketName("bucket") .accountId("account-id") .partition("partition") .region("region") .build(); assertEquals("bucket", bucketResource.bucketName()); assertEquals(Optional.of("account-id"), bucketResource.accountId()); assertEquals(Optional.of("partition"), bucketResource.partition()); assertEquals(Optional.of("region"), bucketResource.region()); assertEquals(S3ControlResourceType.BUCKET.toString(), bucketResource.type()); } @Test(expected = NullPointerException.class) public void buildWithMissingBucketName() { S3ControlBucketResource.builder().build(); } @Test public void equals_allProperties() { S3OutpostResource parentResource = S3OutpostResource.builder() .outpostId("1234") .accountId("account-id") .partition("partition") .region("region") .build(); S3ControlBucketResource bucketResource1 = S3ControlBucketResource.builder() .bucketName("bucket") .parentS3Resource(parentResource) .build(); S3ControlBucketResource bucketResource2 = S3ControlBucketResource.builder() .bucketName("bucket") .parentS3Resource(parentResource) .build(); S3ControlBucketResource bucketResource3 = S3ControlBucketResource.builder() .bucketName("bucket") .accountId("account-id") .partition("different-partition") .region("region") .build(); assertEquals(bucketResource1, bucketResource2); assertNotEquals(bucketResource1, bucketResource3); } @Test public void hashcode_allProperties() { S3OutpostResource parentResource = S3OutpostResource.builder() .outpostId("1234") .accountId("account-id") .partition("partition") .region("region") .build(); S3ControlBucketResource bucketResource1 = S3ControlBucketResource.builder() .bucketName("bucket") .parentS3Resource(parentResource) .build(); S3ControlBucketResource bucketResource2 = S3ControlBucketResource.builder() .bucketName("bucket") .parentS3Resource(parentResource) .build(); S3ControlBucketResource bucketResource3 = S3ControlBucketResource.builder() .bucketName("bucket") .accountId("account-id") .partition("different-partition") .region("region") .build(); assertEquals(bucketResource1.hashCode(), bucketResource2.hashCode()); assertNotEquals(bucketResource1.hashCode(), bucketResource3.hashCode()); } @Test public void buildWithOutpostParent() { S3OutpostResource parentResource = S3OutpostResource.builder() .outpostId("1234") .accountId("account-id") .partition("partition") .region("region") .build(); S3ControlBucketResource bucketResource = S3ControlBucketResource.builder() .bucketName("bucket") .parentS3Resource(parentResource) .build(); assertEquals(Optional.of("account-id"), bucketResource.accountId()); assertEquals(Optional.of("partition"), bucketResource.partition()); assertEquals(Optional.of("region"), bucketResource.region()); assertEquals("bucket", bucketResource.bucketName()); assertEquals("bucket", bucketResource.type()); assertEquals(Optional.of(parentResource), bucketResource.parentS3Resource()); } @Test public void buildWithInvalidParent_shouldThrowException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("parentS3Resource"); S3BucketResource invalidParent = S3BucketResource.builder() .bucketName("bucket") .build(); S3ControlBucketResource.builder() .parentS3Resource(invalidParent) .bucketName("bucketName") .build(); } @Test public void hasParentAndRegion_shouldThrowException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("has parent resource"); S3OutpostResource parentResource = S3OutpostResource.builder() .outpostId("1234") .accountId("account-id") .partition("partition") .region("region") .build(); S3ControlBucketResource.builder() .parentS3Resource(parentResource) .region("us-east-1") .bucketName("bucketName") .build(); } @Test public void hasParentAndPartition_shouldThrowException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("has parent resource"); S3OutpostResource parentResource = S3OutpostResource.builder() .outpostId("1234") .accountId("account-id") .partition("partition") .region("region") .build(); S3ControlBucketResource.builder() .parentS3Resource(parentResource) .partition("partition") .bucketName("bucketName") .build(); } @Test public void hasParentAndAccountId_shouldThrowException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("has parent resource"); S3OutpostResource parentResource = S3OutpostResource.builder() .outpostId("1234") .accountId("account-id") .partition("partition") .region("region") .build(); S3ControlBucketResource.builder() .parentS3Resource(parentResource) .accountId("account-id") .bucketName("bucketName") .build(); } }
4,658
0
Create_ds/aws-sdk-java-v2/services/s3control/src/test/java/software/amazon/awssdk/services/s3control/internal
Create_ds/aws-sdk-java-v2/services/s3control/src/test/java/software/amazon/awssdk/services/s3control/internal/interceptors/PayloadSigningInterceptorTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3control.internal.interceptors; import static org.assertj.core.api.Assertions.assertThat; import java.util.Optional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.signer.S3SignerExecutionAttribute; import software.amazon.awssdk.core.Protocol; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.async.AsyncRequestBody; 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.http.SdkHttpRequest; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3control.S3ControlClient; public class PayloadSigningInterceptorTest { private SdkHttpRequest request; @BeforeEach public void setup() { request = SdkHttpFullRequest.builder() .protocol(Protocol.HTTPS.toString()) .method(SdkHttpMethod.POST) .host(S3ControlClient.serviceMetadata().endpointFor(Region.US_EAST_1).toString()) .build(); } @Test public void modifyHttpContent_AddsExecutionAttributeAndPayload() { PayloadSigningInterceptor interceptor = new PayloadSigningInterceptor(); ExecutionAttributes executionAttributes = new ExecutionAttributes(); Optional<RequestBody> modified = interceptor.modifyHttpContent(new Context(request, null), executionAttributes); assertThat(modified.isPresent()).isTrue(); assertThat(modified.get().contentLength()).isEqualTo(0); assertThat(executionAttributes.getAttribute(S3SignerExecutionAttribute.ENABLE_PAYLOAD_SIGNING)).isTrue(); } @Test public void modifyHttpContent_DoesNotReplaceBody() { PayloadSigningInterceptor interceptor = new PayloadSigningInterceptor(); ExecutionAttributes executionAttributes = new ExecutionAttributes(); Optional<RequestBody> modified = interceptor.modifyHttpContent(new Context(request, RequestBody.fromString("hello")), executionAttributes); assertThat(modified.isPresent()).isTrue(); assertThat(modified.get().contentLength()).isEqualTo(5); assertThat(executionAttributes.getAttribute(S3SignerExecutionAttribute.ENABLE_PAYLOAD_SIGNING)).isTrue(); } public final class Context implements software.amazon.awssdk.core.interceptor.Context.ModifyHttpRequest { private final SdkHttpRequest request; private final RequestBody requestBody; public Context(SdkHttpRequest request, RequestBody requestBody) { this.request = request; this.requestBody = requestBody; } @Override public SdkRequest request() { return null; } @Override public SdkHttpRequest httpRequest() { return request; } @Override public Optional<RequestBody> requestBody() { return Optional.ofNullable(requestBody); } @Override public Optional<AsyncRequestBody> asyncRequestBody() { return Optional.empty(); } } }
4,659
0
Create_ds/aws-sdk-java-v2/services/s3control/src/test/java/software/amazon/awssdk/services/s3control/internal/functionaltests
Create_ds/aws-sdk-java-v2/services/s3control/src/test/java/software/amazon/awssdk/services/s3control/internal/functionaltests/signing/UrlEncodingTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3control.internal.functionaltests.signing; 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.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static org.assertj.core.api.Assertions.assertThat; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.net.URI; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3control.S3ControlClient; public class UrlEncodingTest { private static final String EXPECTED_URL = "/v20180820/jobs/id"; private S3ControlClient s3Control; private ExecutionAttributeInterceptor interceptor; @Rule public WireMockRule mockServer = new WireMockRule(0); protected S3ControlClient buildClient() { URI uri = URI.create("http://localhost:" + mockServer.port()); this.interceptor = new ExecutionAttributeInterceptor(uri); return S3ControlClient.builder() .credentialsProvider(() -> AwsBasicCredentials.create("test", "test")) .region(Region.US_WEST_2) .overrideConfiguration(o -> o.addExecutionInterceptor(this.interceptor)) .build(); } @Before public void methodSetUp() { s3Control = buildClient(); } @Test public void any_request_should_set_double_url_encode_to_false() { stubFor(get(urlMatching(EXPECTED_URL)).willReturn(aResponse().withBody("<xml></xml>").withStatus(200))); s3Control.describeJob(b -> b.accountId("123456789012").jobId("id")); assertThat(interceptor.signerDoubleUrlEncode()).isNotNull(); assertThat(interceptor.signerDoubleUrlEncode()).isFalse(); } /** * In addition to checking the signing attribute, the interceptor sets the endpoint since * S3 control prepends the account id to the host name and wiremock won't intercept the request */ private static class ExecutionAttributeInterceptor implements ExecutionInterceptor { private final URI rerouteEndpoint; private Boolean signerDoubleUrlEncode; ExecutionAttributeInterceptor(URI rerouteEndpoint) { this.rerouteEndpoint = rerouteEndpoint; } @Override public void beforeExecution(Context.BeforeExecution context, ExecutionAttributes executionAttributes) { signerDoubleUrlEncode = executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNER_DOUBLE_URL_ENCODE); } @Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { SdkHttpRequest request = context.httpRequest(); return request.toBuilder().uri(rerouteEndpoint).build(); } public Boolean signerDoubleUrlEncode() { return signerDoubleUrlEncode; } } }
4,660
0
Create_ds/aws-sdk-java-v2/services/s3control/src/test/java/software/amazon/awssdk/services/s3control/internal/functionaltests
Create_ds/aws-sdk-java-v2/services/s3control/src/test/java/software/amazon/awssdk/services/s3control/internal/functionaltests/arns/S3OutpostBucketArnTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3control.internal.functionaltests.arns; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.containing; 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.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3control.S3ControlClient; import software.amazon.awssdk.utils.http.SdkHttpUtils; public class S3OutpostBucketArnTest extends S3ControlWireMockTestBase { private S3ControlClient s3Control; @Rule public ExpectedException exception = ExpectedException.none(); private static final String URL_PREFIX = "/v20180820/bucket/"; private static final String EXPECTED_HOST = "s3-outposts.%s.amazonaws.com"; @Before public void methodSetUp() { s3Control = buildClient(); } @Test public void malformedArn_MissingBucketSegment_shouldThrowException() { S3ControlClient s3ControlForTest = buildClientCustom().build(); String bucketArn = "arn:aws:s3-outposts:us-west-2:123456789012:outpost:op-01234567890123456"; exception.expect(SdkClientException.class); exception.expectMessage("Invalid ARN: Expected a 4-component resource"); s3ControlForTest.getBucket(b -> b.bucket(bucketArn)); } @Test public void malformedArn_missingOutpostId_shouldThrowException() { S3ControlClient s3ControlForTest = buildClientCustom().build(); String bucketArn = "arn:aws:s3-outposts:us-west-2:123456789012:outpost"; exception.expect(SdkClientException.class); exception.expectMessage("Invalid ARN: The Outpost Id was not set"); s3ControlForTest.getBucket(b -> b.bucket(bucketArn)); } @Test public void malformedArn_missingOutpostIdAndBucketName_shouldThrowException() { S3ControlClient s3ControlForTest = buildClientCustom().build(); String bucketArn = "arn:aws:s3-outposts:us-west-2:123456789012:outpost:bucket"; exception.expect(SdkClientException.class); exception.expectMessage("Invalid ARN: Expected a 4-component resource"); s3ControlForTest.getBucket(b -> b.bucket(bucketArn)); } @Test public void malformedArn_missingBucketName_shouldThrowException() { S3ControlClient s3ControlForTest = buildClientCustom().build(); String bucketArn = "arn:aws:s3-outposts:us-west-2:123456789012:outpost:op-01234567890123456:bucket"; exception.expect(SdkClientException.class); exception.expectMessage("Invalid ARN: expected a bucket name"); s3ControlForTest.getBucket(b -> b.bucket(bucketArn)); } @Test public void bucketArnDifferentRegionNoConfigFlag_throwsIllegalArgumentException() { S3ControlClient s3ControlForTest = initializedBuilder().region(Region.of("us-west-2")).build(); String bucketArn = "arn:aws:s3-outposts:us-east-1:123456789012:outpost:op-01234567890123456:bucket:mybucket"; exception.expect(SdkClientException.class); exception.expectMessage("Invalid configuration: region from ARN `us-east-1` does not match client region `us-west-2` and UseArnRegion is `false`"); s3ControlForTest.getBucket(b -> b.bucket(bucketArn)); } @Test public void bucketArnInvalidPartition_throwsIllegalArgumentException() { S3ControlClient s3ControlForTest = initializedBuilder().region(Region.of("us-west-2")).serviceConfiguration(b -> b.useArnRegionEnabled(true)).build(); String bucketArn = "arn:aws-cn:s3-outposts:cn-north-1:123456789012:outpost:op-01234567890123456:bucket:mybucket"; exception.expect(SdkClientException.class); exception.expectMessage("Client was configured for partition `aws` but ARN has `aws-cn`"); s3ControlForTest.getBucket(b -> b.bucket(bucketArn)); } @Test public void bucketArn_conflictingAccountIdPresent_shouldThrowException() { S3ControlClient s3ControlForTest = initializedBuilder().region(Region.of("us-west-2")).build(); String bucketArn = "arn:aws:s3-outposts:us-west-2:123456789012:outpost:op-01234567890123456:bucket:mybucket"; exception.expect(SdkClientException.class); exception.expectMessage("Invalid ARN: the accountId specified in the ARN (`123456789012`) does not match the parameter (`1234`)"); s3ControlForTest.getBucket(b -> b.bucket(bucketArn).accountId("1234")); } @Test public void bucketArnUSRegion() { S3ControlClient s3ControlForTest = initializedBuilder().region(Region.of("us-west-2")).build(); String bucketArn = "arn:aws:s3-outposts:us-west-2:123456789012:outpost:op-01234567890123456:bucket:mybucket"; String expectedUrl = getUrl(bucketArn); stubResponse(expectedUrl); s3ControlForTest.getBucket(b -> b.bucket(bucketArn)); verifyRequest("us-west-2", expectedUrl); } @Test public void bucketArn_GovRegion() { S3ControlClient s3ControlForTest = initializedBuilder().region(Region.of("us-gov-east-1")).build(); String bucketArn = "arn:aws-us-gov:s3-outposts:us-gov-east-1:123456789012:outpost:op-01234567890123456:bucket:mybucket"; String expectedUrl = getUrl(bucketArn); stubResponse(expectedUrl); s3ControlForTest.getBucket(b -> b.bucket(bucketArn)); verifyRequest("us-gov-east-1", expectedUrl); } @Test public void bucketArn_futureRegion_US() { S3ControlClient s3ControlForTest = initializedBuilder().region(Region.of("us-future-1")).build(); String bucketArn = "arn:aws:s3-outposts:us-future-1:123456789012:outpost:op-01234567890123456:bucket:mybucket"; String expectedUrl = getUrl(bucketArn); stubResponse(expectedUrl); s3ControlForTest.getBucket(b -> b.bucket(bucketArn)); verifyRequest("us-future-1", expectedUrl); } @Test public void bucketArn_futureRegion_CN() { S3ControlClient s3ControlForTest = initializedBuilder().region(Region.of("cn-future-1")).build(); String bucketArn = "arn:aws-cn:s3-outposts:cn-future-1:123456789012:outpost:op-01234567890123456:bucket:mybucket"; String expectedUrl = getUrl(bucketArn); stubResponse(expectedUrl); s3ControlForTest.getBucket(b -> b.bucket(bucketArn)); verifyOutpostRequest("cn-future-1", expectedUrl, "s3-outposts.cn-future-1.amazonaws.com.cn"); } @Test public void bucketArnDifferentRegion_useArnRegionSet_shouldUseRegionFromArn() { String bucketArn = "arn:aws:s3-outposts:us-west-2:123456789012:outpost:op-01234567890123456:bucket:mybucket"; String expectedUrl = getUrl(bucketArn); stubResponse(expectedUrl); S3ControlClient s3WithUseArnRegion = initializedBuilder().region(Region.of("us-east-1")).serviceConfiguration(b -> b.useArnRegionEnabled(true)).build(); s3WithUseArnRegion.getBucket(b -> b.bucket(bucketArn)); verifyRequest("us-west-2", expectedUrl); } @Test public void outpostBucketArn_listAccessPoints() { S3ControlClient s3ControlForTest = initializedBuilder().region(Region.of("us-west-2")).build(); String bucketArn = "arn:aws:s3-outposts:us-west-2:123456789012:outpost:op-01234567890123456:bucket:mybucket"; String expectedUrl = "/v20180820/accesspoint?bucket=" + SdkHttpUtils.urlEncode(bucketArn); stubFor(get(urlEqualTo(expectedUrl)).willReturn(aResponse().withBody("<xml></xml>").withStatus(200))); s3ControlForTest.listAccessPoints(b -> b.bucket(bucketArn)); verify(getRequestedFor(urlEqualTo(expectedUrl)) .withHeader("authorization", containing("us-west-2/s3-outposts/aws4_request")) .withHeader("x-amz-outpost-id", equalTo("op-01234567890123456")) .withHeader("x-amz-account-id", equalTo("123456789012"))); assertThat(getRecordedEndpoints().size(), is(1)); assertThat(getRecordedEndpoints().get(0).getHost(), is(String.format(EXPECTED_HOST, "us-west-2"))); } @Test public void outpostBucketArn_createAccessPoint() { S3ControlClient s3ControlForTest = initializedBuilder().region(Region.of("us-west-2")).build(); String bucketArn = "arn:aws:s3-outposts:us-west-2:123456789012:outpost:op-01234567890123456:bucket:mybucket"; stubFor(put(urlEqualTo("/v20180820/accesspoint/name")).willReturn(aResponse().withBody("<xml></xml>").withStatus(200))); String bucketResponseXml = String.format("<Bucket>%s</Bucket>", bucketArn); s3ControlForTest.createAccessPoint(b -> b.bucket(bucketArn).name("name")); verify(putRequestedFor(urlEqualTo("/v20180820/accesspoint/name")) .withRequestBody(containing(bucketResponseXml)) .withHeader("authorization", containing("us-west-2/s3-outposts/aws4_request")) .withHeader("x-amz-outpost-id", equalTo("op-01234567890123456")) .withHeader("x-amz-account-id", equalTo("123456789012"))); assertThat(getRecordedEndpoints().size(), is(1)); assertThat(getRecordedEndpoints().get(0).getHost(), is(String.format(EXPECTED_HOST, "us-west-2"))); } private void verifyRequest(String region, String expectedUrl) { verifyOutpostRequest(region, expectedUrl, String.format(EXPECTED_HOST, region)); } private String getUrl(String arn) { return URL_PREFIX + SdkHttpUtils.urlEncode(arn); } }
4,661
0
Create_ds/aws-sdk-java-v2/services/s3control/src/test/java/software/amazon/awssdk/services/s3control/internal/functionaltests
Create_ds/aws-sdk-java-v2/services/s3control/src/test/java/software/amazon/awssdk/services/s3control/internal/functionaltests/arns/S3OutpostAccessPointArnTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3control.internal.functionaltests.arns; import static com.github.tomakehurst.wiremock.client.WireMock.containing; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3control.S3ControlClient; import software.amazon.awssdk.services.s3control.S3ControlClientBuilder; import software.amazon.awssdk.utils.http.SdkHttpUtils; public class S3OutpostAccessPointArnTest extends S3ControlWireMockTestBase { private S3ControlClient s3; private static final String URL_PREFIX = "/v20180820/accesspoint/"; @Rule public ExpectedException exception = ExpectedException.none(); @Before public void methodSetUp() { s3 = buildClient(); } @Test public void dualstackEnabled_shouldThrowException() { S3ControlClient s3ControlForTest = buildClientCustom().serviceConfiguration(b -> b.dualstackEnabled(true)).build(); String outpostArn = "arn:aws:s3-outposts:us-west-2:123456789012:outpost:op-01234567890123456:accesspoint:myaccesspoint"; exception.expect(SdkClientException.class); exception.expectMessage("Outpost Access Points do not support dual-stack"); s3ControlForTest.getAccessPoint(b -> b.name(outpostArn)); } @Test public void dualstackEnabledViaClient_shouldThrowException() { S3ControlClient s3ControlForTest = buildClientCustom().dualstackEnabled(true).build(); String outpostArn = "arn:aws:s3-outposts:us-west-2:123456789012:outpost:op-01234567890123456:accesspoint:myaccesspoint"; exception.expect(SdkClientException.class); exception.expectMessage("Outpost Access Points do not support dual-stack"); s3ControlForTest.getAccessPoint(b -> b.name(outpostArn)); } @Test public void malformedArn_MissingOutpostSegment_shouldThrowException() { S3ControlClient s3ControlForTest = buildClientCustom().build(); String outpostArn = "arn:aws:s3-outposts:us-west-2:123456789012:outpost"; exception.expect(SdkClientException.class); exception.expectMessage("Invalid ARN: The Outpost Id was not set"); s3ControlForTest.getAccessPoint(b -> b.name(outpostArn)); } @Test public void malformedArn_MissingAccessPointSegment_shouldThrowException() { S3ControlClient s3ControlForTest = buildClientCustom().build(); String outpostArn = "arn:aws:s3-outposts:us-west-2:123456789012:outpost:op-01234567890123456"; exception.expect(SdkClientException.class); exception.expectMessage("Invalid ARN: Expected a 4-component resource"); s3ControlForTest.getAccessPoint(b -> b.name(outpostArn)); } @Test public void malformedArn_MissingAccessPointName_shouldThrowException() { S3ControlClient s3ControlForTest = buildClientCustom().build(); String outpostArn = "arn:aws:s3-outposts:us-west-2:123456789012:outpost:myaccesspoint"; exception.expect(SdkClientException.class); exception.expectMessage("Expected a 4-component resource"); s3ControlForTest.getAccessPoint(b -> b.name(outpostArn)); } @Test public void bucketArnDifferentRegionNoConfigFlag_throwsIllegalArgumentException() { S3ControlClient s3ControlForTest = initializedBuilder().region(Region.of("us-west-2")).build(); String outpostArn = "arn:aws:s3-outposts:us-east-1:123456789012:outpost:op-01234567890123456:accesspoint:myaccesspoint"; exception.expect(SdkClientException.class); exception.expectMessage("Invalid configuration: region from ARN `us-east-1` does not match client region `us-west-2` and UseArnRegion is `false`"); s3ControlForTest.getAccessPoint(b -> b.name(outpostArn)); } @Test public void outpostArn_accountIdPresent_shouldThrowException() { S3ControlClient s3Control = initializedBuilderForAccessPoint().region(Region.of("us-future-1")).build(); String outpostArn = "arn:aws:s3-outposts:us-future-1:123456789012:outpost:op-01234567890123456:accesspoint:myaccesspoint"; exception.expect(SdkClientException.class); exception.expectMessage("Invalid ARN: the accountId specified in the ARN (`123456789012`) does not match the parameter (`1234`)"); s3Control.getAccessPoint(b -> b.name(outpostArn).accountId("1234")); } @Test public void nonArn_shouldNotRedirect() { S3ControlClient s3Control = initializedBuilderForAccessPoint().region(Region.of("us-west-2")).build(); String name = "myaccesspoint"; String expectedUrl = getUrl(name); stubResponse(expectedUrl); s3Control.getAccessPoint(b -> b.name(name).accountId("123456789012")); String expectedHost = "123456789012.s3-control.us-west-2.amazonaws.com"; verify(getRequestedFor(urlEqualTo(expectedUrl)) .withHeader("authorization", containing("us-west-2/s3/aws4_request")) .withHeader("x-amz-account-id", equalTo("123456789012"))); assertThat(getRecordedEndpoints().size(), is(1)); assertThat(getRecordedEndpoints().get(0).getHost(), is(expectedHost)); } @Test public void outpostArnUSRegion() { S3ControlClient s3Control = initializedBuilderForAccessPoint().region(Region.of("us-west-2")).build(); String outpostArn = "arn:aws:s3-outposts:us-west-2:123456789012:outpost:op-01234567890123456:accesspoint:myaccesspoint"; String expectedHost = "s3-outposts.us-west-2.amazonaws.com"; String expectedUrl = getUrl(outpostArn); stubResponse(expectedUrl); s3Control.getAccessPoint(b -> b.name(outpostArn).accountId("123456789012")); verifyOutpostRequest("us-west-2", expectedUrl, expectedHost); } @Test public void outpostArn_GovRegion() { S3ControlClient s3Control = initializedBuilderForAccessPoint().region(Region.of("us-gov-east-1")).build(); String outpostArn = "arn:aws-us-gov:s3-outposts:us-gov-east-1:123456789012:outpost:op-01234567890123456:accesspoint" + ":myaccesspoint"; String expectedHost = "s3-outposts.us-gov-east-1.amazonaws.com"; String expectedUrl = getUrl(outpostArn); stubResponse(expectedUrl); s3Control.getAccessPoint(b -> b.name(outpostArn)); verifyOutpostRequest("us-gov-east-1", expectedUrl, expectedHost); } @Test public void outpostArn_futureRegion_US() { S3ControlClient s3Control = initializedBuilderForAccessPoint().region(Region.of("us-future-1")).build(); String outpostArn = "arn:aws:s3-outposts:us-future-1:123456789012:outpost:op-01234567890123456:accesspoint:myaccesspoint"; String expectedHost = "s3-outposts.us-future-1.amazonaws.com"; String expectedUrl = getUrl(outpostArn); stubResponse(expectedUrl); s3Control.getAccessPoint(b -> b.name(outpostArn)); verifyOutpostRequest("us-future-1", expectedUrl, expectedHost); } @Test public void outpostArn_futureRegion_CN() { S3ControlClient s3Control = initializedBuilderForAccessPoint().region(Region.of("cn-future-1")).build(); String outpostArn = "arn:aws-cn:s3-outposts:cn-future-1:123456789012:outpost:op-01234567890123456:accesspoint" + ":myaccesspoint"; String expectedHost = "s3-outposts.cn-future-1.amazonaws.com.cn"; String expectedUrl = getUrl(outpostArn); stubResponse(expectedUrl); s3Control.getAccessPoint(b -> b.name(outpostArn)); verifyOutpostRequest("cn-future-1", expectedUrl, expectedHost); } @Test public void outpostArnDifferentRegion_useArnRegionSet_shouldUseRegionFromArn() { String outpostArn = "arn:aws:s3-outposts:us-east-1:123456789012:outpost:op-01234567890123456:accesspoint:myaccesspoint"; String expectedHost = "s3-outposts.us-east-1.amazonaws.com"; String expectedUrl = getUrl(outpostArn); stubResponse(expectedUrl); S3ControlClient s3WithUseArnRegion = initializedBuilderForAccessPoint().region(Region.of("us-west-2")).serviceConfiguration(b -> b.useArnRegionEnabled(true)).build(); s3WithUseArnRegion.getAccessPoint(b -> b.name(outpostArn)); verifyOutpostRequest("us-east-1", expectedUrl, expectedHost); } private S3ControlClientBuilder initializedBuilderForAccessPoint() { return initializedBuilder(); } private String getUrl(String arn) { return URL_PREFIX + SdkHttpUtils.urlEncode(arn); } }
4,662
0
Create_ds/aws-sdk-java-v2/services/s3control/src/test/java/software/amazon/awssdk/services/s3control/internal/functionaltests
Create_ds/aws-sdk-java-v2/services/s3control/src/test/java/software/amazon/awssdk/services/s3control/internal/functionaltests/arns/S3ControlWireMockTestBase.java
/* * Copyright 2011-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3control.internal.functionaltests.arns; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.containing; 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.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import com.github.tomakehurst.wiremock.core.WireMockConfiguration; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.net.URI; import java.util.List; import org.junit.Rule; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3control.S3ControlClient; import software.amazon.awssdk.services.s3control.S3ControlClientBuilder; /** * Base class for tests that use a WireMock server */ public abstract class S3ControlWireMockTestBase { private S3ControlWireMockRerouteInterceptor s3ControlWireMockRequestHandler; @Rule public WireMockRule mockServer = new WireMockRule(new WireMockConfiguration().port(0).httpsPort(0)); protected String getEndpoint() { return "http://localhost:" + mockServer.port(); } protected S3ControlClient buildClient() { this.s3ControlWireMockRequestHandler = new S3ControlWireMockRerouteInterceptor(URI.create(getEndpoint())); return initializedBuilder().build(); } protected S3ControlClientBuilder buildClientCustom() { this.s3ControlWireMockRequestHandler = new S3ControlWireMockRerouteInterceptor(URI.create(getEndpoint())); return initializedBuilder(); } protected S3ControlClient buildClientWithCustomEndpoint(String serviceEndpoint, String signingRegion) { this.s3ControlWireMockRequestHandler = new S3ControlWireMockRerouteInterceptor(URI.create(getEndpoint())); return initializedBuilder().region(Region.of(signingRegion)).endpointOverride(URI.create(serviceEndpoint)).build(); } protected S3ControlClientBuilder initializedBuilder() { return S3ControlClient.builder() .credentialsProvider(() -> AwsBasicCredentials.create("test", "test")) .region(Region.US_WEST_2) .overrideConfiguration(o -> o.addExecutionInterceptor(this.s3ControlWireMockRequestHandler)); } protected List<SdkHttpRequest> getRecordedRequests() { return this.s3ControlWireMockRequestHandler.getRecordedRequests(); } protected List<URI> getRecordedEndpoints() { return this.s3ControlWireMockRequestHandler.getRecordedEndpoints(); } protected void verifyOutpostRequest(String region, String expectedUrl, String expectedHost) { verify(getRequestedFor(urlEqualTo(expectedUrl)) .withHeader("Authorization", containing(String.format("%s/s3-outposts/aws4_request", region))) .withHeader("x-amz-outpost-id", equalTo("op-01234567890123456")) .withHeader("x-amz-account-id", equalTo("123456789012"))); assertThat(getRecordedEndpoints().size(), is(1)); assertThat(getRecordedEndpoints().get(0).getHost(), is(expectedHost)); } protected void stubResponse(String url) { stubFor(get(urlMatching(url)).willReturn(aResponse().withBody("<xml></xml>").withStatus(200))); } protected void verifyS3ControlRequest(String region, String expectedUrl, String expectedHost) { verify(getRequestedFor(urlEqualTo(expectedUrl)).withHeader("Authorization", containing(String.format("%s/s3/aws4_request", region))) .withHeader("x-amz-account-id", equalTo("123456789012"))); assertThat(getRecordedEndpoints().size(), is(1)); assertThat(getRecordedEndpoints().get(0).getHost(), is(expectedHost)); } }
4,663
0
Create_ds/aws-sdk-java-v2/services/s3control/src/test/java/software/amazon/awssdk/services/s3control/internal/functionaltests
Create_ds/aws-sdk-java-v2/services/s3control/src/test/java/software/amazon/awssdk/services/s3control/internal/functionaltests/arns/NonArnOutpostRequestTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3control.internal.functionaltests.arns; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.containing; 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.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.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3control.S3ControlClient; public class NonArnOutpostRequestTest extends S3ControlWireMockTestBase { private S3ControlClient s3; private static final String EXPECTED_URL = "/v20180820/bucket"; @Before public void methodSetUp() { s3 = buildClient(); } @Test public void listRegionalBuckets_outpostIdNotNull_shouldRedirect() { S3ControlClient s3Control = initializedBuilder().region(Region.of("us-west-2")).build(); stubFor(get(urlMatching(EXPECTED_URL)).willReturn(aResponse().withBody("<xml></xml>").withStatus(200))); s3Control.listRegionalBuckets(b -> b.outpostId("op-01234567890123456").accountId("123456789012")); String expectedHost = "s3-outposts.us-west-2.amazonaws.com"; verifyOutpostRequest("us-west-2", EXPECTED_URL, expectedHost); } @Test public void listRegionalBuckets_outpostIdNull_shouldNotRedirect() { S3ControlClient s3Control = initializedBuilder().region(Region.of("us-west-2")).build(); stubFor(get(urlMatching(EXPECTED_URL)).willReturn(aResponse().withBody("<xml></xml>").withStatus(200))); s3Control.listRegionalBuckets(b -> b.accountId("123456789012")); String expectedHost = "123456789012.s3-control.us-west-2.amazonaws.com"; verifyS3ControlRequest("us-west-2", EXPECTED_URL, expectedHost); } @Test public void createBucketRequest_outpostIdNotNull_shouldRedirect() { S3ControlClient s3Control = initializedBuilder().region(Region.of("us-west-2")).build(); stubFor(put(urlMatching("/v20180820/bucket/test")).willReturn(aResponse().withBody("<xml></xml>").withStatus(200))); s3Control.createBucket(b -> b.outpostId("op-01234567890123456").bucket("test")); String expectedHost = "s3-outposts.us-west-2.amazonaws.com"; verify(putRequestedFor(urlEqualTo("/v20180820/bucket/test")) .withHeader("Authorization", containing("us-west-2/s3-outposts/aws4_request")) .withHeader("x-amz-outpost-id", equalTo("op-01234567890123456"))); assertThat(getRecordedEndpoints().size(), is(1)); assertThat(getRecordedEndpoints().get(0).getHost(), is(expectedHost)); } @Test public void createBucketRequest_outpostIdNull_shouldNotRedirect() { S3ControlClient s3Control = initializedBuilder().region(Region.of("us-west-2")).build(); stubFor(put(urlMatching("/v20180820/bucket/test")).willReturn(aResponse().withBody("<xml></xml>").withStatus(200))); s3Control.createBucket(b -> b.bucket("test")); String expectedHost = "s3-control.us-west-2.amazonaws.com"; verify(putRequestedFor(urlEqualTo("/v20180820/bucket/test")).withHeader("Authorization", containing("us-west-2/s3/aws4_request"))); assertThat(getRecordedEndpoints().size(), is(1)); assertThat(getRecordedEndpoints().get(0).getHost(), is(expectedHost)); } }
4,664
0
Create_ds/aws-sdk-java-v2/services/s3control/src/test/java/software/amazon/awssdk/services/s3control/internal/functionaltests
Create_ds/aws-sdk-java-v2/services/s3control/src/test/java/software/amazon/awssdk/services/s3control/internal/functionaltests/arns/S3AccessPointArnTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3control.internal.functionaltests.arns; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3control.S3ControlClient; public class S3AccessPointArnTest extends S3ControlWireMockTestBase { private S3ControlClient s3Control; private static final String EXPECTED_URL = "/v20180820/accesspoint/myendpoint"; @Rule public ExpectedException exception = ExpectedException.none(); @Before public void methodSetUp() { s3Control = buildClient(); } @Test public void malformedArn_MissingOutpostSegment_shouldThrowException() { String accessPointArn = "arn:aws:s3-outposts:us-west-2:123456789012:outpost"; exception.expect(SdkClientException.class); exception.expectMessage("Invalid ARN: The Outpost Id was not set"); s3Control.getAccessPoint(b -> b.name(accessPointArn)); } @Test public void malformedArn_MissingAccessPointSegment_shouldThrowException() { String accessPointArn = "arn:aws:s3-outposts:us-west-2:123456789012:outpost:op-01234567890123456"; exception.expect(SdkClientException.class); exception.expectMessage("Invalid ARN: Expected a 4-component resource"); s3Control.getAccessPoint(b -> b.name(accessPointArn)); } @Test public void malformedArn_MissingAccessPointName_shouldThrowException() { String accessPointArn = "arn:aws:s3-outposts:us-west-2:123456789012:outpost:myaccesspoint"; exception.expect(SdkClientException.class); exception.expectMessage("Invalid ARN: Expected a 4-component resource"); s3Control.getAccessPoint(b -> b.name(accessPointArn)); } @Test public void bucketArnDifferentRegionNoConfigFlag_throwsIllegalArgumentException() { S3ControlClient s3ControlCustom = initializedBuilder().region(Region.of("us-east-1")).build(); String accessPointArn = "arn:aws:s3-outposts:us-west-2:123456789012:outpost:op-01234567890123456:accesspoint" + ":myaccesspoint"; exception.expect(SdkClientException.class); exception.expectMessage("Invalid configuration: region from ARN `us-west-2` does not match client region `us-east-1` and UseArnRegion is `false`"); s3ControlCustom.getAccessPoint(b -> b.name(accessPointArn)); } }
4,665
0
Create_ds/aws-sdk-java-v2/services/s3control/src/test/java/software/amazon/awssdk/services/s3control/internal/functionaltests
Create_ds/aws-sdk-java-v2/services/s3control/src/test/java/software/amazon/awssdk/services/s3control/internal/functionaltests/arns/S3ControlWireMockRerouteInterceptor.java
package software.amazon.awssdk.services.s3control.internal.functionaltests.arns; import java.net.URI; import java.util.ArrayList; import java.util.List; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.http.SdkHttpRequest; /** * Class javadoc */ public class S3ControlWireMockRerouteInterceptor implements ExecutionInterceptor { private final URI rerouteEndpoint; private final List<SdkHttpRequest> recordedRequests = new ArrayList<>(); private final List<URI> recordedEndpoints = new ArrayList<URI>(); S3ControlWireMockRerouteInterceptor(URI rerouteEndpoint) { this.rerouteEndpoint = rerouteEndpoint; } @Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { SdkHttpRequest request = context.httpRequest(); recordedEndpoints.add(request.getUri()); recordedRequests.add(request); return request.toBuilder().uri(rerouteEndpoint).build(); } public List<SdkHttpRequest> getRecordedRequests() { return recordedRequests; } public List<URI> getRecordedEndpoints() { return recordedEndpoints; } }
4,666
0
Create_ds/aws-sdk-java-v2/services/s3control/src/it/java
Create_ds/aws-sdk-java-v2/services/s3control/src/it/java/software.amazon.awssdk.services.s3control/S3ControlIntegrationTestBase.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3control; import static org.assertj.core.api.Assertions.assertThat; import java.util.Iterator; import java.util.List; import org.junit.BeforeClass; import software.amazon.awssdk.core.ClientType; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.S3AsyncClientBuilder; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.S3ClientBuilder; import software.amazon.awssdk.services.s3.model.BucketLocationConstraint; import software.amazon.awssdk.services.s3.model.CreateBucketConfiguration; import software.amazon.awssdk.services.s3.model.CreateBucketRequest; import software.amazon.awssdk.services.s3.model.DeleteBucketRequest; import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; import software.amazon.awssdk.services.s3.model.ListObjectVersionsRequest; import software.amazon.awssdk.services.s3.model.ListObjectVersionsResponse; import software.amazon.awssdk.services.s3.model.ListObjectsRequest; import software.amazon.awssdk.services.s3.model.ListObjectsResponse; import software.amazon.awssdk.services.s3.model.NoSuchBucketException; import software.amazon.awssdk.services.s3.model.S3Exception; import software.amazon.awssdk.services.s3.model.S3Object; import software.amazon.awssdk.services.sts.StsClient; import software.amazon.awssdk.testutils.Waiter; import software.amazon.awssdk.testutils.service.AwsTestBase; /** * Base class for S3 Control integration tests. Loads AWS credentials from a properties * file and creates an S3 client for callers to use. */ public class S3ControlIntegrationTestBase extends AwsTestBase { protected static final Region DEFAULT_REGION = Region.US_WEST_2; /** * The S3 client for all tests to use. */ protected static S3Client s3; protected static S3AsyncClient s3Async; protected static StsClient sts; protected static String accountId; /** * Loads the AWS account info for the integration tests and creates an S3 * client for tests to use. */ @BeforeClass public static void setUp() throws Exception { s3 = s3ClientBuilder().build(); s3Async = s3AsyncClientBuilder().build(); sts = StsClient.builder() .region(DEFAULT_REGION) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .build(); accountId = sts.getCallerIdentity().account(); } protected static S3ClientBuilder s3ClientBuilder() { return S3Client.builder() .region(DEFAULT_REGION) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .overrideConfiguration(o -> o.addExecutionInterceptor( new UserAgentVerifyingExecutionInterceptor("Apache", ClientType.SYNC))); } protected static S3AsyncClientBuilder s3AsyncClientBuilder() { return S3AsyncClient.builder() .region(DEFAULT_REGION) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .overrideConfiguration(o -> o.addExecutionInterceptor( new UserAgentVerifyingExecutionInterceptor("NettyNio", ClientType.ASYNC))); } protected static void createBucket(String bucketName) { createBucket(bucketName, 0); } private static void createBucket(String bucketName, int retryCount) { try { s3.createBucket( CreateBucketRequest.builder() .bucket(bucketName) .createBucketConfiguration( CreateBucketConfiguration.builder() .locationConstraint(BucketLocationConstraint.US_WEST_2) .build()) .build()); } catch (S3Exception e) { System.err.println("Error attempting to create bucket: " + bucketName); if (e.awsErrorDetails().errorCode().equals("BucketAlreadyOwnedByYou")) { System.err.printf("%s bucket already exists, likely leaked by a previous run\n", bucketName); } else if (e.awsErrorDetails().errorCode().equals("TooManyBuckets")) { System.err.println("Printing all buckets for debug:"); s3.listBuckets().buckets().forEach(System.err::println); if (retryCount < 2) { System.err.println("Retrying..."); createBucket(bucketName, retryCount + 1); } else { throw e; } } else { throw e; } } } protected static void deleteBucketAndAllContents(String bucketName) { deleteBucketAndAllContents(s3, bucketName); } private static class UserAgentVerifyingExecutionInterceptor implements ExecutionInterceptor { private final String clientName; private final ClientType clientType; public UserAgentVerifyingExecutionInterceptor(String clientName, ClientType clientType) { this.clientName = clientName; this.clientType = clientType; } @Override public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) { assertThat(context.httpRequest().firstMatchingHeader("User-Agent").get()).containsIgnoringCase("io/" + clientType.name()); assertThat(context.httpRequest().firstMatchingHeader("User-Agent").get()).containsIgnoringCase("http/" + clientName); } } public static void deleteBucketAndAllContents(S3Client s3, String bucketName) { try { System.out.println("Deleting S3 bucket: " + bucketName); ListObjectsResponse response = Waiter.run(() -> s3.listObjects(r -> r.bucket(bucketName))) .ignoringException(NoSuchBucketException.class) .orFail(); List<S3Object> objectListing = response.contents(); if (objectListing != null) { while (true) { for (Iterator<?> iterator = objectListing.iterator(); iterator.hasNext(); ) { S3Object objectSummary = (S3Object) iterator.next(); s3.deleteObject(DeleteObjectRequest.builder().bucket(bucketName).key(objectSummary.key()).build()); } if (response.isTruncated()) { objectListing = s3.listObjects(ListObjectsRequest.builder() .bucket(bucketName) .marker(response.marker()) .build()) .contents(); } else { break; } } } ListObjectVersionsResponse versions = s3 .listObjectVersions(ListObjectVersionsRequest.builder().bucket(bucketName).build()); if (versions.deleteMarkers() != null) { versions.deleteMarkers().forEach(v -> s3.deleteObject(DeleteObjectRequest.builder() .versionId(v.versionId()) .bucket(bucketName) .key(v.key()) .build())); } if (versions.versions() != null) { versions.versions().forEach(v -> s3.deleteObject(DeleteObjectRequest.builder() .versionId(v.versionId()) .bucket(bucketName) .key(v.key()) .build())); } s3.deleteBucket(DeleteBucketRequest.builder().bucket(bucketName).build()); } catch (Exception e) { System.err.println("Failed to delete bucket: " + bucketName); e.printStackTrace(); } } }
4,667
0
Create_ds/aws-sdk-java-v2/services/s3control/src/it/java
Create_ds/aws-sdk-java-v2/services/s3control/src/it/java/software.amazon.awssdk.services.s3control/S3MrapIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3control; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import static software.amazon.awssdk.utils.StringUtils.isEmpty; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.stream.Stream; 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.signer.AwsSignerExecutionAttribute; import software.amazon.awssdk.auth.signer.S3SignerExecutionAttribute; import software.amazon.awssdk.auth.signer.internal.SignerConstant; import software.amazon.awssdk.awscore.presigner.PresignedRequest; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.retry.backoff.FixedDelayBackoffStrategy; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.core.waiters.Waiter; import software.amazon.awssdk.core.waiters.WaiterAcceptor; import software.amazon.awssdk.http.HttpExecuteRequest; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.apache.ApacheHttpClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.S3Configuration; import software.amazon.awssdk.services.s3.model.BucketAlreadyOwnedByYouException; import software.amazon.awssdk.services.s3.model.NoSuchKeyException; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.model.UploadPartRequest; import software.amazon.awssdk.services.s3.presigner.S3Presigner; import software.amazon.awssdk.services.s3.presigner.model.PresignedGetObjectRequest; import software.amazon.awssdk.services.s3control.model.BucketAlreadyExistsException; import software.amazon.awssdk.services.s3control.model.CreateMultiRegionAccessPointInput; import software.amazon.awssdk.services.s3control.model.GetMultiRegionAccessPointResponse; import software.amazon.awssdk.services.s3control.model.ListMultiRegionAccessPointsResponse; import software.amazon.awssdk.services.s3control.model.MultiRegionAccessPointStatus; import software.amazon.awssdk.services.sts.StsClient; import software.amazon.awssdk.utils.IoUtils; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.StringInputStream; public class S3MrapIntegrationTest extends S3ControlIntegrationTestBase { private static final Logger log = Logger.loggerFor(S3MrapIntegrationTest.class); private static final String SIGV4A_CHUNKED_PAYLOAD_SIGNING = "STREAMING-AWS4-ECDSA-P256-SHA256-PAYLOAD"; private static final String SIGV4_CHUNKED_PAYLOAD_SIGNING = "STREAMING-AWS4-HMAC-SHA256-PAYLOAD"; private static final String UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD"; private static final Region REGION = Region.US_WEST_2; private static String bucket; private static String mrapName; private static final String KEY = "aws-java-sdk-small-test-object"; private static final String CONTENT = "A short string for a small test object"; private static final int RETRY_TIMES = 10; private static final int RETRY_DELAY_IN_SECONDS = 30; private static S3ControlClient s3control; private static CaptureRequestInterceptor captureInterceptor; private static String mrapAlias; private static StsClient stsClient; private static S3Client s3Client; private static S3Client s3ClientWithPayloadSigning; @BeforeAll public static void setupFixture() { captureInterceptor = new CaptureRequestInterceptor(); s3control = S3ControlClient.builder() .region(REGION) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .build(); s3Client = mrapEnabledS3Client(Collections.singletonList(captureInterceptor)); s3ClientWithPayloadSigning = mrapEnabledS3Client(Arrays.asList(captureInterceptor, new PayloadSigningInterceptor())); stsClient = StsClient.builder() .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .region(REGION) .build(); accountId = stsClient.getCallerIdentity().account(); bucket = "do-not-delete-s3mraptest-" + accountId; mrapName = "javaintegtest" + accountId; log.info(() -> "bucket " + bucket); createBucketIfNotExist(bucket); createMrapIfNotExist(accountId, mrapName); mrapAlias = getMrapAliasAndVerify(accountId, mrapName); } @ParameterizedTest(name = "{index}:key = {1}, {0}") @MethodSource("keys") public void when_callingMrapWithDifferentPaths_unsignedPayload_requestIsAccepted(String name, String key, String expected) { putGetDeleteObjectMrap(s3Client, UNSIGNED_PAYLOAD, key, expected); } @ParameterizedTest(name = "{index}:key = {1}, {0}") @MethodSource("keys") public void when_callingMrapWithDifferentPaths_signedPayload_requestIsAccepted(String name, String key, String expected) { putGetDeleteObjectMrap(s3ClientWithPayloadSigning, SIGV4A_CHUNKED_PAYLOAD_SIGNING, key, expected); } @ParameterizedTest(name = "{index}:key = {1}, {0}") @MethodSource("keys") public void when_callingS3WithDifferentPaths_unsignedPayload_requestIsAccepted(String name, String key, String expected) { putGetDeleteObjectStandard(s3Client, UNSIGNED_PAYLOAD, key, expected); } @ParameterizedTest(name = "{index}:key = {1}, {0}") @MethodSource("keys") public void when_callingS3WithDifferentPaths_signedPayload_requestIsAccepted(String name, String key, String expected) { putGetDeleteObjectStandard(s3ClientWithPayloadSigning, SIGV4_CHUNKED_PAYLOAD_SIGNING, key, expected); } @Test public void when_creatingPresignedMrapUrl_getRequestWorks() { S3Presigner presigner = s3Presigner(); PresignedGetObjectRequest presignedGetObjectRequest = presigner.presignGetObject(p -> p.getObjectRequest(r -> r.bucket(constructMrapArn(accountId, mrapAlias)).key(KEY)) .signatureDuration(Duration.ofMinutes(10))); deleteObjectIfExists(s3Client, constructMrapArn(accountId, mrapAlias), KEY); s3Client.putObject(r -> r.bucket(constructMrapArn(accountId, mrapAlias)).key(KEY), RequestBody.fromString(CONTENT)); String object = applyPresignedUrl(presignedGetObjectRequest, null); assertEquals(CONTENT, object); verifySigv4aRequest(captureInterceptor.request(), UNSIGNED_PAYLOAD); } public void putGetDeleteObjectMrap(S3Client testClient, String payloadSigningTag, String key, String expected) { deleteObjectIfExists(testClient, constructMrapArn(accountId, mrapAlias), key); testClient.putObject(r -> r.bucket(constructMrapArn(accountId, mrapAlias)).key(key), RequestBody.fromString(CONTENT)); verifySigv4aRequest(captureInterceptor.request(), payloadSigningTag); String object = testClient.getObjectAsBytes(r -> r.bucket(constructMrapArn(accountId, mrapAlias)).key(key)).asString(StandardCharsets.UTF_8); assertEquals(CONTENT, object); verifySigv4aRequest(captureInterceptor.request(), UNSIGNED_PAYLOAD); testClient.deleteObject(r -> r.bucket(constructMrapArn(accountId, mrapAlias)).key(key)); verifySigv4aRequest(captureInterceptor.request(), UNSIGNED_PAYLOAD); assertThat(captureInterceptor.normalizePath).isNotNull().isEqualTo(false); assertThat(captureInterceptor.request.encodedPath()).isEqualTo(expected); } public void putGetDeleteObjectStandard(S3Client testClient, String payloadSigningTag, String key, String expected) { deleteObjectIfExists(testClient, bucket, key); testClient.putObject(r -> r.bucket(bucket).key(key), RequestBody.fromString(CONTENT)); verifySigv4Request(captureInterceptor.request(), payloadSigningTag); String object = testClient.getObjectAsBytes(r -> r.bucket(bucket).key(key)).asString(StandardCharsets.UTF_8); assertEquals(CONTENT, object); verifySigv4Request(captureInterceptor.request(), UNSIGNED_PAYLOAD); testClient.deleteObject(r -> r.bucket(bucket).key(key)); verifySigv4Request(captureInterceptor.request(), UNSIGNED_PAYLOAD); assertThat(captureInterceptor.normalizePath).isNotNull().isEqualTo(false); assertThat(captureInterceptor.request.encodedPath()).isEqualTo(expected); } private void verifySigv4aRequest(SdkHttpRequest signedRequest, String payloadSigningTag) { assertThat(signedRequest.headers().get("Authorization").get(0)).contains("AWS4-ECDSA-P256-SHA256"); assertThat(signedRequest.headers().get("Host").get(0)).isEqualTo(constructMrapHostname(mrapAlias)); assertThat(signedRequest.headers().get("x-amz-content-sha256").get(0)).isEqualTo(payloadSigningTag); assertThat(signedRequest.headers().get("X-Amz-Date").get(0)).isNotEmpty(); assertThat(signedRequest.headers().get("X-Amz-Region-Set").get(0)).isEqualTo("*"); } private void verifySigv4Request(SdkHttpRequest signedRequest, String payloadSigningTag) { assertThat(signedRequest.headers().get("Authorization").get(0)).contains(SignerConstant.AWS4_SIGNING_ALGORITHM); assertThat(signedRequest.headers().get("Host").get(0)).isEqualTo(String.format("%s.s3.%s.amazonaws.com", bucket, REGION.id())); assertThat(signedRequest.headers().get("x-amz-content-sha256").get(0)).isEqualTo(payloadSigningTag); assertThat(signedRequest.headers().get("X-Amz-Date").get(0)).isNotEmpty(); } private static Stream<Arguments> keys() { return Stream.of( Arguments.of("Slash -> unchanged", "/", "//"), Arguments.of("Single segment with initial slash -> unchanged", "/foo", "//foo"), Arguments.of("Single segment no slash -> slash prepended", "foo", "/foo"), Arguments.of("Multiple segments -> unchanged", "/foo/bar", "//foo/bar"), Arguments.of("Multiple segments with trailing slash -> unchanged", "/foo/bar/", "//foo/bar/"), Arguments.of("Multiple segments, urlEncoded slash -> encodes percent", "/foo%2Fbar", "//foo%252Fbar"), Arguments.of("Single segment, dot -> should remove dot", "/.", "//."), Arguments.of("Multiple segments with dot -> should remove dot", "/foo/./bar", "//foo/./bar"), Arguments.of("Multiple segments with ending dot -> should remove dot and trailing slash", "/foo/bar/.", "//foo/bar/."), Arguments.of("Multiple segments with dots -> should remove dots and preceding segment", "/foo/bar/../baz", "//foo/bar/../baz"), Arguments.of("First segment has colon -> unchanged, url encoded first", "foo:/bar", "/foo%3A/bar"), Arguments.of("Multiple segments, urlEncoded slash -> encodes percent", "/foo%2F.%2Fbar", "//foo%252F.%252Fbar"), Arguments.of("No url encode, Multiple segments with dot -> unchanged", "/foo/./bar", "//foo/./bar"), Arguments.of("Multiple segments with dots -> unchanged", "/foo/bar/../baz", "//foo/bar/../baz"), Arguments.of("double slash", "//H", "///H"), Arguments.of("double slash in middle", "A//H", "/A//H") ); } private String constructMrapArn(String account, String mrapAlias) { return String.format("arn:aws:s3::%s:accesspoint:%s", account, mrapAlias); } private String constructMrapHostname(String mrapAlias) { return String.format("%s.accesspoint.s3-global.amazonaws.com", mrapAlias); } private S3Presigner s3Presigner() { return S3Presigner.builder() .region(REGION) .serviceConfiguration(S3Configuration.builder() .useArnRegionEnabled(true) .checksumValidationEnabled(false) .build()) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .build(); } private static void createMrapIfNotExist(String account, String mrapName) { software.amazon.awssdk.services.s3control.model.Region mrapRegion = software.amazon.awssdk.services.s3control.model.Region.builder().bucket(bucket).build(); boolean mrapNotExists = s3control.listMultiRegionAccessPoints(r -> r.accountId(account)) .accessPoints().stream() .noneMatch(a -> a.name().equals(S3MrapIntegrationTest.mrapName)); if (mrapNotExists) { CreateMultiRegionAccessPointInput details = CreateMultiRegionAccessPointInput.builder() .name(mrapName) .regions(mrapRegion) .build(); log.info(() -> "Creating MRAP: " + mrapName); s3control.createMultiRegionAccessPoint(r -> r.accountId(account).details(details)); waitForResourceCreation(mrapName); } } private static void waitForResourceCreation(String mrapName) throws IllegalStateException { Waiter<ListMultiRegionAccessPointsResponse> waiter = Waiter.builder(ListMultiRegionAccessPointsResponse.class) .addAcceptor(WaiterAcceptor.successOnResponseAcceptor(r -> r.accessPoints().stream().findFirst().filter(mrap -> mrap.name().equals(mrapName) && mrap.status().equals(MultiRegionAccessPointStatus.READY)).isPresent() )) .addAcceptor(WaiterAcceptor.retryOnResponseAcceptor(i -> true)) .overrideConfiguration(b -> b.maxAttempts(RETRY_TIMES).backoffStrategy(FixedDelayBackoffStrategy.create(Duration.ofSeconds(RETRY_DELAY_IN_SECONDS)))) .build(); waiter.run(() -> s3control.listMultiRegionAccessPoints(r -> r.accountId(accountId))); } public static String getMrapAliasAndVerify(String account, String mrapName) { GetMultiRegionAccessPointResponse mrap = s3control.getMultiRegionAccessPoint(r -> r.accountId(account).name(mrapName)); assertThat(mrap.accessPoint()).isNotNull(); assertThat(mrap.accessPoint().name()).isEqualTo(mrapName); log.info(() -> "Alias: " + mrap.accessPoint().alias()); return mrap.accessPoint().alias(); } private String applyPresignedUrl(PresignedRequest presignedRequest, String content) { try { HttpExecuteRequest.Builder builder = HttpExecuteRequest.builder().request(presignedRequest.httpRequest()); if (!isEmpty(content)) { builder.contentStreamProvider(() -> new StringInputStream(content)); } HttpExecuteRequest request = builder.build(); HttpExecuteResponse response = ApacheHttpClient.create().prepareRequest(request).call(); return response.responseBody() .map(stream -> invokeSafely(() -> IoUtils.toUtf8String(stream))) .orElseThrow(() -> new IOException("No input stream")); } catch (IOException e) { log.error(() -> "Error occurred ", e); } return null; } private static S3Client mrapEnabledS3Client(List<ExecutionInterceptor> executionInterceptors) { return S3Client.builder() .region(REGION) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .serviceConfiguration(S3Configuration.builder() .useArnRegionEnabled(true) .build()) .overrideConfiguration(o -> o.executionInterceptors(executionInterceptors)) .build(); } private void deleteObjectIfExists(S3Client s31, String bucket1, String key) { System.out.println(bucket1); try { s31.deleteObject(r -> r.bucket(bucket1).key(key)); } catch (NoSuchKeyException e) { } } private static void createBucketIfNotExist(String bucket) { try { s3Client.createBucket(b -> b.bucket(bucket)); s3Client.waiter().waitUntilBucketExists(b -> b.bucket(bucket)); } catch (BucketAlreadyOwnedByYouException | BucketAlreadyExistsException e) { // ignore } } private static class CaptureRequestInterceptor implements ExecutionInterceptor { private SdkHttpRequest request; private Boolean normalizePath; public SdkHttpRequest request() { return request; } @Override public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) { this.request = context.httpRequest(); this.normalizePath = executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNER_NORMALIZE_PATH); } } private static class PayloadSigningInterceptor implements ExecutionInterceptor { public Optional<RequestBody> modifyHttpContent(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { SdkRequest sdkRequest = context.request(); if (sdkRequest instanceof PutObjectRequest || sdkRequest instanceof UploadPartRequest) { executionAttributes.putAttribute(S3SignerExecutionAttribute.ENABLE_PAYLOAD_SIGNING, true); } if (!context.requestBody().isPresent() && context.httpRequest().method().equals(SdkHttpMethod.POST)) { return Optional.of(RequestBody.fromBytes(new byte[0])); } return context.requestBody(); } } }
4,668
0
Create_ds/aws-sdk-java-v2/services/s3control/src/it/java
Create_ds/aws-sdk-java-v2/services/s3control/src/it/java/software.amazon.awssdk.services.s3control/S3AsyncAccessPointsIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3control; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertNotNull; import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName; import java.util.StringJoiner; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.sts.StsClient; public class S3AsyncAccessPointsIntegrationTest extends S3ControlIntegrationTestBase { private static final String BUCKET = temporaryBucketName(S3AsyncAccessPointsIntegrationTest.class); private static final String AP_NAME = "java-sdk-" + System.currentTimeMillis(); private static final String KEY = "some-key"; private static S3ControlAsyncClient s3control; private static StsClient sts; private static String accountId; @BeforeClass public static void setupFixture() { createBucket(BUCKET); s3control = S3ControlAsyncClient.builder() .region(Region.US_WEST_2) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .build(); sts = StsClient.builder() .region(Region.US_WEST_2) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .build(); accountId = sts.getCallerIdentity().account(); s3control.createAccessPoint(r -> r.accountId(accountId) .bucket(BUCKET) .name(AP_NAME)) .join(); } @AfterClass public static void tearDown() { s3control.deleteAccessPoint(b -> b.accountId(accountId).name(AP_NAME)).join(); deleteBucketAndAllContents(BUCKET); } @Test public void accessPointOperation_nonArns() { assertNotNull(s3control.listAccessPoints(b -> b.bucket(BUCKET).accountId(accountId).maxResults(1)).join()); assertNotNull(s3control.getAccessPoint(b -> b.name(AP_NAME).accountId(accountId)).join()); } @Test public void transfer_Succeeds_UsingAccessPoint() { StringJoiner apArn = new StringJoiner(":"); apArn.add("arn").add("aws").add("s3").add("us-west-2").add(accountId).add("accesspoint").add(AP_NAME); s3.putObject(PutObjectRequest.builder() .bucket(apArn.toString()) .key(KEY) .build(), RequestBody.fromString("helloworld")); String objectContent = s3.getObjectAsBytes(GetObjectRequest.builder() .bucket(apArn.toString()) .key(KEY) .build()).asUtf8String(); assertThat(objectContent).isEqualTo("helloworld"); } }
4,669
0
Create_ds/aws-sdk-java-v2/services/s3control/src/it/java
Create_ds/aws-sdk-java-v2/services/s3control/src/it/java/software.amazon.awssdk.services.s3control/S3ControlIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3control; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Fail.fail; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.junit.After; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.services.s3control.model.DeletePublicAccessBlockRequest; import software.amazon.awssdk.services.s3control.model.GetPublicAccessBlockResponse; import software.amazon.awssdk.services.s3control.model.NoSuchPublicAccessBlockConfigurationException; import software.amazon.awssdk.services.s3control.model.PutPublicAccessBlockResponse; import software.amazon.awssdk.services.s3control.model.S3ControlException; import software.amazon.awssdk.services.sts.StsClient; import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase; public class S3ControlIntegrationTest extends AwsIntegrationTestBase { private String accountId; private static final String INVALID_ACCOUNT_ID = "1"; private S3ControlClient client; @Before public void setup() { StsClient sts = StsClient.create(); accountId = sts.getCallerIdentity().account(); client = S3ControlClient.builder() .overrideConfiguration(o -> o.addExecutionInterceptor(new AssertPayloadIsSignedExecutionInterceptor())) .build(); } @After public void tearDown() { try { client.deletePublicAccessBlock(DeletePublicAccessBlockRequest.builder().accountId(accountId).build()); } catch (Exception ignore) { } } @Test public void putGetAndDeletePublicAccessBlock_ValidAccount() throws InterruptedException { PutPublicAccessBlockResponse result = client.putPublicAccessBlock(r -> r.accountId(accountId) .publicAccessBlockConfiguration(r2 -> r2.blockPublicAcls(true) .ignorePublicAcls(true))); assertNotNull(result); // Wait a bit for the put to take affect Thread.sleep(5000); GetPublicAccessBlockResponse config = client.getPublicAccessBlock(r -> r.accountId(accountId)); assertTrue(config.publicAccessBlockConfiguration().blockPublicAcls()); assertTrue(config.publicAccessBlockConfiguration().ignorePublicAcls()); assertNotNull(client.deletePublicAccessBlock(r -> r.accountId(accountId))); } @Test public void putPublicAccessBlock_NoSuchAccount() { try { assertNotNull(client.putPublicAccessBlock(r -> r.accountId(INVALID_ACCOUNT_ID) .publicAccessBlockConfiguration(r2 -> r2.restrictPublicBuckets(true)))); fail("Expected exception"); } catch (S3ControlException e) { assertThat(e.awsErrorDetails().errorCode()).isEqualTo("AccessDenied"); assertNotNull(e.requestId()); } } @Test public void getPublicAccessBlock_NoSuchAccount() { try { client.getPublicAccessBlock(r -> r.accountId(INVALID_ACCOUNT_ID)); fail("Expected exception"); } catch (S3ControlException e) { assertThat(e.awsErrorDetails().errorCode()).isEqualTo("AccessDenied"); assertNotNull(e.requestId()); } } @Test public void getPublicAccessBlock_NoSuchPublicAccessBlock() { try { client.getPublicAccessBlock(r -> r.accountId(accountId)); fail("Expected exception"); } catch (S3ControlException e) { assertThat(e.awsErrorDetails().errorCode()).isEqualTo("NoSuchPublicAccessBlockConfiguration"); assertThat(e).isInstanceOf(NoSuchPublicAccessBlockConfigurationException.class); assertNotNull(e.requestId()); } } @Test public void listJobs_InvalidRequest() { try { client.listJobs(r -> r.accountId(accountId).jobStatusesWithStrings("test")); fail("Expected exception"); } catch (S3ControlException e) { assertThat(e.awsErrorDetails().errorCode()).isEqualTo("InvalidRequest"); assertNotNull(e.requestId()); } } @Test public void describeJob_InvalidRequest() { try { client.describeJob(r -> r.accountId(accountId).jobId("someid")); fail("Expected exception"); } catch (S3ControlException e) { assertThat(e.awsErrorDetails().errorCode()).isEqualTo("InvalidRequest"); assertNotNull(e.requestId()); } } @Test public void deletePublicAccessBlock_NoSuchAccount() { try { client.deletePublicAccessBlock(r -> r.accountId(INVALID_ACCOUNT_ID)); fail("Expected exception"); } catch (S3ControlException e) { assertThat(e.awsErrorDetails().errorCode()).isEqualTo("AccessDenied"); assertNotNull(e.requestId()); } } /** * Request handler to assert that payload signing is enabled. */ private static final class AssertPayloadIsSignedExecutionInterceptor implements ExecutionInterceptor { @Override public void afterTransmission(Context.AfterTransmission context, ExecutionAttributes executionAttributes) { SdkHttpFullRequest request = (SdkHttpFullRequest) context.httpRequest(); assertThat(context.httpRequest().headers().get("x-amz-content-sha256").get(0)).doesNotContain("UNSIGNED-PAYLOAD"); } } }
4,670
0
Create_ds/aws-sdk-java-v2/services/s3control/src/it/java
Create_ds/aws-sdk-java-v2/services/s3control/src/it/java/software.amazon.awssdk.services.s3control/S3AccessPointsIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3control; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertNotNull; import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import java.io.IOException; import java.time.Duration; import java.util.StringJoiner; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.http.HttpExecuteRequest; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.apache.ApacheHttpClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.presigner.S3Presigner; import software.amazon.awssdk.services.sts.StsClient; import software.amazon.awssdk.utils.IoUtils; import software.amazon.awssdk.utils.StringInputStream; public class S3AccessPointsIntegrationTest extends S3ControlIntegrationTestBase { private static final String BUCKET = temporaryBucketName(S3AccessPointsIntegrationTest.class); private static final String AP_NAME = "java-sdk-" + System.currentTimeMillis(); private static final String KEY = "some-key"; private static S3ControlClient s3control; private static StsClient sts; private static String accountId; @BeforeClass public static void setupFixture() { createBucket(BUCKET); s3control = S3ControlClient.builder() .region(Region.US_WEST_2) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .build(); sts = StsClient.builder() .region(Region.US_WEST_2) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .build(); accountId = sts.getCallerIdentity().account(); s3control.createAccessPoint(r -> r.accountId(accountId) .bucket(BUCKET) .name(AP_NAME)); } @AfterClass public static void tearDown() { s3control.deleteAccessPoint(b -> b.accountId(accountId).name(AP_NAME)); deleteBucketAndAllContents(BUCKET); } @Test public void transfer_Succeeds_UsingAccessPoint() { StringJoiner apArn = new StringJoiner(":"); apArn.add("arn").add("aws").add("s3").add("us-west-2").add(accountId).add("accesspoint").add(AP_NAME); s3.putObject(PutObjectRequest.builder() .bucket(apArn.toString()) .key(KEY) .build(), RequestBody.fromString("helloworld")); String objectContent = s3.getObjectAsBytes(GetObjectRequest.builder() .bucket(apArn.toString()) .key(KEY) .build()).asUtf8String(); assertThat(objectContent).isEqualTo("helloworld"); } @Test public void transfer_Succeeds_UsingAccessPoint_CrossRegion() { S3Client s3DifferentRegion = s3ClientBuilder().region(Region.US_EAST_1).serviceConfiguration(c -> c.useArnRegionEnabled(true)).build(); StringJoiner apArn = new StringJoiner(":"); apArn.add("arn").add("aws").add("s3").add("us-west-2").add(accountId).add("accesspoint").add(AP_NAME); s3DifferentRegion.putObject(PutObjectRequest.builder() .bucket(apArn.toString()) .key(KEY) .build(), RequestBody.fromString("helloworld")); String objectContent = s3DifferentRegion.getObjectAsBytes(GetObjectRequest.builder() .bucket(apArn.toString()) .key(KEY) .build()).asUtf8String(); assertThat(objectContent).isEqualTo("helloworld"); } @Test public void uploadAndDownloadWithPresignedUrlWorks() throws IOException { String accessPointArn = new StringJoiner(":").add("arn").add("aws").add("s3").add("us-west-2").add(accountId) .add("accesspoint").add(AP_NAME).toString(); String key = "foo/a0A!-_.*'()&@:,$=+?; \n\\^`<>{}[]#%\"~|山"; testAccessPointPresigning(accessPointArn, key); } private void testAccessPointPresigning(String accessPointArn, String key) throws IOException { String data = "Hello"; S3Presigner presigner = S3Presigner.builder().region(Region.US_WEST_2).build(); SdkHttpRequest presignedPut = presigner.presignPutObject(r -> r.signatureDuration(Duration.ofDays(7)) .putObjectRequest(por -> por.bucket(accessPointArn) .key(key))) .httpRequest(); SdkHttpRequest presignedGet = presigner.presignGetObject(r -> r.signatureDuration(Duration.ofDays(7)) .getObjectRequest(gor -> gor.bucket(accessPointArn) .key(key))) .httpRequest(); try (SdkHttpClient client = ApacheHttpClient.create()) { client.prepareRequest(HttpExecuteRequest.builder() .request(presignedPut) .contentStreamProvider(() -> new StringInputStream(data)) .build()) .call(); HttpExecuteResponse getResult = client.prepareRequest(HttpExecuteRequest.builder() .request(presignedGet) .build()) .call(); String result = getResult.responseBody() .map(stream -> invokeSafely(() -> IoUtils.toUtf8String(stream))) .orElseThrow(AssertionError::new); assertThat(result).isEqualTo(data); } } @Test public void accessPointOperation_nonArns() { assertNotNull(s3control.listAccessPoints(b -> b.bucket(BUCKET).accountId(accountId).maxResults(1))); assertNotNull(s3control.getAccessPoint(b -> b.name(AP_NAME).accountId(accountId))); } }
4,671
0
Create_ds/aws-sdk-java-v2/services/s3control/src/main/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/s3control/src/main/java/software/amazon/awssdk/services/s3control/S3ControlBucketResource.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3control; import java.util.Objects; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.services.s3.internal.resource.S3OutpostResource; import software.amazon.awssdk.services.s3.internal.resource.S3Resource; import software.amazon.awssdk.services.s3.internal.resource.S3ResourceType; import software.amazon.awssdk.services.s3control.internal.S3ControlResourceType; import software.amazon.awssdk.utils.Validate; /** * An {@link S3Resource} that represents an bucket. */ @SdkInternalApi public final class S3ControlBucketResource implements S3Resource { private final String partition; private final String region; private final String accountId; private final String bucketName; private final S3Resource parentS3Resource; private S3ControlBucketResource(Builder b) { this.bucketName = Validate.notBlank(b.bucketName, "bucketName"); if (b.parentS3Resource == null) { this.parentS3Resource = null; this.partition = b.partition; this.region = b.region; this.accountId = b.accountId; } else { this.parentS3Resource = validateParentS3Resource(b.parentS3Resource); Validate.isNull(b.partition, "partition cannot be set on builder if it has parent resource"); Validate.isNull(b.region, "region cannot be set on builder if it has parent resource"); Validate.isNull(b.accountId, "accountId cannot be set on builder if it has parent resource"); this.partition = parentS3Resource.partition().orElse(null); this.region = parentS3Resource.region().orElse(null); this.accountId = parentS3Resource.accountId().orElse(null); } } /** * Get a new builder for this class. * @return A newly initialized instance of a builder. */ public static Builder builder() { return new Builder(); } /** * Gets the resource type for this bucket. * @return This will always return "bucket_name". */ @Override public String type() { return S3ControlResourceType.BUCKET.toString(); } /** * Gets the AWS partition name associated with this bucket (e.g.: 'aws'). * @return the name of the partition. */ @Override public Optional<String> partition() { return Optional.of(this.partition); } /** * Gets the AWS region name associated with this bucket (e.g.: 'us-east-1'). * @return the name of the region or null if the region has not been specified (e.g. the resource is in the * global namespace). */ @Override public Optional<String> region() { return Optional.of(this.region); } /** * Gets the AWS account ID associated with this bucket. * @return the AWS account ID or null if the account ID has not been specified. */ @Override public Optional<String> accountId() { return Optional.of(this.accountId); } /** * Gets the name of the bucket. * @return the name of the bucket. */ public String bucketName() { return this.bucketName; } /** * Gets the optional parent s3 resource * @return the parent s3 resource if exists, otherwise null */ @Override public Optional<S3Resource> parentS3Resource() { return Optional.ofNullable(parentS3Resource); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } S3ControlBucketResource that = (S3ControlBucketResource) o; if (!Objects.equals(partition, that.partition)) { return false; } if (!Objects.equals(region, that.region)) { return false; } if (!Objects.equals(accountId, that.accountId)) { return false; } if (!bucketName.equals(that.bucketName)) { return false; } return Objects.equals(parentS3Resource, that.parentS3Resource); } @Override public int hashCode() { int result = partition != null ? partition.hashCode() : 0; result = 31 * result + (region != null ? region.hashCode() : 0); result = 31 * result + (accountId != null ? accountId.hashCode() : 0); result = 31 * result + bucketName.hashCode(); result = 31 * result + (parentS3Resource != null ? parentS3Resource.hashCode() : 0); return result; } /** * A builder for {@link S3ControlBucketResource} objects. */ public static final class Builder { private String partition; private String region; private String accountId; private String bucketName; private S3Resource parentS3Resource; private Builder() { } /** * The AWS partition associated with the bucket. */ public Builder partition(String partition) { this.partition = partition; return this; } public void setRegion(String region) { this.region = region; } /** * The AWS region associated with the bucket. This property is optional. */ public Builder region(String region) { this.region = region; return this; } /** * The AWS account ID associated with the bucket. This property is optional. */ public Builder accountId(String accountId) { this.accountId = accountId; return this; } /** * The name of the S3 bucket. */ public Builder bucketName(String bucketName) { this.bucketName = bucketName; return this; } /** * The S3 resource this access point is associated with (contained within). Only {@link S3OutpostResource} and * is a valid parent resource types. */ public Builder parentS3Resource(S3Resource parentS3Resource) { this.parentS3Resource = parentS3Resource; return this; } /** * Builds an instance of {@link S3ControlBucketResource}. */ public S3ControlBucketResource build() { return new S3ControlBucketResource(this); } } private S3Resource validateParentS3Resource(S3Resource parentS3Resource) { if (!S3ResourceType.OUTPOST.toString().equals(parentS3Resource.type())) { throw new IllegalArgumentException("Invalid 'parentS3Resource' type. An S3 bucket resource must be " + "associated with an outpost parent resource."); } return parentS3Resource; } }
4,672
0
Create_ds/aws-sdk-java-v2/services/s3control/src/main/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/s3control/src/main/java/software/amazon/awssdk/services/s3control/S3ControlConfiguration.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3control; import java.util.Optional; import java.util.function.Supplier; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.core.ServiceConfiguration; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileFileSupplier; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * S3 Control specific configuration allowing customers to enable FIPS or * dualstack. */ @SdkPublicApi @Immutable @ThreadSafe public final class S3ControlConfiguration implements ServiceConfiguration, ToCopyableBuilder<S3ControlConfiguration.Builder, S3ControlConfiguration> { /** * S3 FIPS mode is by default not enabled */ private static final boolean DEFAULT_FIPS_MODE_ENABLED = false; /** * S3 Dualstack endpoint is by default not enabled */ private static final boolean DEFAULT_DUALSTACK_ENABLED = false; private static final boolean DEFAULT_USE_ARN_REGION_ENABLED = false; private final Boolean fipsModeEnabled; private final Boolean dualstackEnabled; private final Boolean useArnRegionEnabled; private final Supplier<ProfileFile> profileFile; private final String profileName; private S3ControlConfiguration(DefaultS3ServiceConfigurationBuilder builder) { this.dualstackEnabled = builder.dualstackEnabled; this.fipsModeEnabled = builder.fipsModeEnabled; this.profileFile = builder.profileFile; this.profileName = builder.profileName; this.useArnRegionEnabled = builder.useArnRegionEnabled; } /** * Create a {@link Builder}, used to create a {@link S3ControlConfiguration}. */ public static Builder builder() { return new DefaultS3ServiceConfigurationBuilder(); } /** * <p> * Returns whether the client has enabled fips mode for accessing S3 Control. * * @return True if client will use FIPS mode. */ public boolean fipsModeEnabled() { return resolveBoolean(fipsModeEnabled, DEFAULT_FIPS_MODE_ENABLED); } /** * <p> * Returns whether the client is configured to use dualstack mode for * accessing S3. If you want to use IPv6 when accessing S3, dualstack * must be enabled. * </p> * * <p> * Dualstack endpoints are disabled by default. * </p> * * @return True if the client will use the dualstack endpoints */ public boolean dualstackEnabled() { return resolveBoolean(dualstackEnabled, DEFAULT_DUALSTACK_ENABLED); } /** * Returns whether the client is configured to make calls to a region specified in an ARN that represents an * S3 resource even if that region is different to the region the client was initialized with. This setting is disabled by * default. * * @return true if use arn region is enabled. */ public boolean useArnRegionEnabled() { return resolveBoolean(useArnRegionEnabled, DEFAULT_USE_ARN_REGION_ENABLED); } private boolean resolveBoolean(Boolean suppliedValue, boolean defaultValue) { return suppliedValue == null ? defaultValue : suppliedValue; } @Override public Builder toBuilder() { return builder() .dualstackEnabled(dualstackEnabled) .fipsModeEnabled(fipsModeEnabled) .useArnRegionEnabled(useArnRegionEnabled) .profileFile(profileFile) .profileName(profileName); } @NotThreadSafe public interface Builder extends CopyableBuilder<Builder, S3ControlConfiguration> { Boolean dualstackEnabled(); /** * Option to enable using the dualstack endpoints when accessing S3. Dualstack * should be enabled if you want to use IPv6. * * <p> * Dualstack endpoints are disabled by default. * </p> * * @see S3ControlConfiguration#dualstackEnabled(). * @deprecated This option has been replaced with {@link S3ControlClientBuilder#dualstackEnabled(Boolean)}. If both are * set, an exception will be thrown. */ @Deprecated Builder dualstackEnabled(Boolean dualstackEnabled); Boolean fipsModeEnabled(); /** * Option to enable using the fips endpoint when accessing S3 Control. * * <p> * FIPS mode is disabled by default. * </p> * * @see S3ControlConfiguration#fipsModeEnabled(). * @deprecated This has been deprecated in favor of {@link S3ControlClientBuilder#fipsEnabled(Boolean)}. If both are * set, an exception will be thrown. */ @Deprecated Builder fipsModeEnabled(Boolean fipsModeEnabled); /** * Option to enable the client to make calls to a region specified in an ARN that represents an S3 resource * even if that region is different to the region the client was initialized with. This setting is disabled by * default. */ Builder useArnRegionEnabled(Boolean arnRegionEnabled); /** * Option to enable the client to make calls to a region specified in an ARN that represents an S3 resource * even if that region is different to the region the client was initialized with. This setting is disabled by * default. */ Boolean useArnRegionEnabled(); ProfileFile profileFile(); /** * The profile file that should be consulted to determine the service-specific default configuration. This is not * currently used by S3 control, but may be in a future SDK version. */ Builder profileFile(ProfileFile profileFile); Supplier<ProfileFile> profileFileSupplier(); /** * The profile file supplier that should be consulted to determine the service-specific default configuration. */ Builder profileFile(Supplier<ProfileFile> profileFile); String profileName(); /** * The profile name that should be consulted to determine the service-specific default configuration. This is not * currently used by S3 control, but may be in a future SDK version. */ Builder profileName(String profileName); } private static final class DefaultS3ServiceConfigurationBuilder implements Builder { private Boolean dualstackEnabled; private Boolean fipsModeEnabled; private Supplier<ProfileFile> profileFile; private String profileName; private Boolean useArnRegionEnabled; @Override public Boolean dualstackEnabled() { return dualstackEnabled; } @Override public Builder dualstackEnabled(Boolean dualstackEnabled) { this.dualstackEnabled = dualstackEnabled; return this; } public void setDualstackEnabled(Boolean dualstackEnabled) { dualstackEnabled(dualstackEnabled); } @Override public Boolean fipsModeEnabled() { return fipsModeEnabled; } @Override public Builder fipsModeEnabled(Boolean fipsModeEnabled) { this.fipsModeEnabled = fipsModeEnabled; return this; } public void setFipsModeEnabled(Boolean fipsModeEnabled) { fipsModeEnabled(fipsModeEnabled); } @Override public Builder useArnRegionEnabled(Boolean arnRegionEnabled) { this.useArnRegionEnabled = arnRegionEnabled; return this; } @Override public Boolean useArnRegionEnabled() { return useArnRegionEnabled; } public void setUseArnRegionEnabled(Boolean useArnRegionEnabled) { useArnRegionEnabled(useArnRegionEnabled); } @Override public ProfileFile profileFile() { return Optional.ofNullable(profileFile) .map(Supplier::get) .orElse(null); } @Override public Builder profileFile(ProfileFile profileFile) { return profileFile(Optional.ofNullable(profileFile) .map(ProfileFileSupplier::fixedProfileFile) .orElse(null)); } @Override public Supplier<ProfileFile> profileFileSupplier() { return profileFile; } @Override public Builder profileFile(Supplier<ProfileFile> profileFile) { this.profileFile = profileFile; return this; } @Override public String profileName() { return profileName; } @Override public Builder profileName(String profileName) { this.profileName = profileName; return this; } @Override public S3ControlConfiguration build() { return new S3ControlConfiguration(this); } } }
4,673
0
Create_ds/aws-sdk-java-v2/services/s3control/src/main/java/software/amazon/awssdk/services/s3control
Create_ds/aws-sdk-java-v2/services/s3control/src/main/java/software/amazon/awssdk/services/s3control/internal/S3ControlArnConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3control.internal; import static software.amazon.awssdk.services.s3.internal.resource.S3ArnUtils.parseOutpostArn; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.arns.Arn; import software.amazon.awssdk.arns.ArnResource; import software.amazon.awssdk.services.s3.internal.resource.ArnConverter; import software.amazon.awssdk.services.s3.internal.resource.IntermediateOutpostResource; import software.amazon.awssdk.services.s3.internal.resource.OutpostResourceType; import software.amazon.awssdk.services.s3.internal.resource.S3AccessPointResource; import software.amazon.awssdk.services.s3.internal.resource.S3OutpostResource; import software.amazon.awssdk.services.s3.internal.resource.S3Resource; import software.amazon.awssdk.services.s3control.S3ControlBucketResource; @SdkInternalApi public final class S3ControlArnConverter implements ArnConverter<S3Resource> { private static final S3ControlArnConverter INSTANCE = new S3ControlArnConverter(); private S3ControlArnConverter() { } /** * Gets a static singleton instance of an {@link S3ControlArnConverter}. * * @return A static instance of an {@link S3ControlArnConverter}. */ public static S3ControlArnConverter getInstance() { return INSTANCE; } @Override public S3Resource convertArn(Arn arn) { S3ControlResourceType s3ResourceType; try { s3ResourceType = arn.resource().resourceType().map(S3ControlResourceType::fromValue) .orElseThrow(() -> new IllegalArgumentException("resource type cannot be null")); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Unknown ARN type '" + arn.resource().resourceType() + "'"); } switch (s3ResourceType) { case OUTPOST: return parseS3OutpostArn(arn); default: throw new IllegalArgumentException("Unknown ARN type '" + arn.resource().resourceType() + "'"); } } private S3Resource parseS3OutpostArn(Arn arn) { IntermediateOutpostResource intermediateOutpostResource = parseOutpostArn(arn); ArnResource outpostSubresource = intermediateOutpostResource.outpostSubresource(); String subResource = outpostSubresource.resource(); OutpostResourceType outpostResourceType; try { outpostResourceType = outpostSubresource.resourceType().map(OutpostResourceType::fromValue) .orElseThrow(() -> new IllegalArgumentException("resource type cannot be " + "null")); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Unknown outpost ARN type '" + outpostSubresource.resourceType() + "'"); } String outpostId = intermediateOutpostResource.outpostId(); switch (outpostResourceType) { case OUTPOST_BUCKET: return S3ControlBucketResource.builder() .bucketName(subResource) .parentS3Resource(S3OutpostResource.builder() .partition(arn.partition()) .region(arn.region().orElse(null)) .accountId(arn.accountId().orElse(null)) .outpostId(outpostId) .build()) .build(); case OUTPOST_ACCESS_POINT: return S3AccessPointResource.builder() .accessPointName(subResource) .parentS3Resource(S3OutpostResource.builder() .partition(arn.partition()) .region(arn.region().orElse(null)) .accountId(arn.accountId().orElse(null)) .outpostId(outpostId) .build()) .build(); default: throw new IllegalArgumentException("Unknown outpost ARN type '" + outpostSubresource.resourceType() + "'"); } } }
4,674
0
Create_ds/aws-sdk-java-v2/services/s3control/src/main/java/software/amazon/awssdk/services/s3control
Create_ds/aws-sdk-java-v2/services/s3control/src/main/java/software/amazon/awssdk/services/s3control/internal/S3ControlResourceType.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3control.internal; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.services.s3.internal.resource.S3Resource; /** * An enum representing the types of resources supported by S3 control. Each resource type below will have a * concrete implementation of {@link S3Resource}. */ @SdkInternalApi public enum S3ControlResourceType { BUCKET("bucket"), OUTPOST("outpost"); private final String value; S3ControlResourceType(String value) { this.value = value; } /** * @return The canonical string value of this resource type. */ @Override public String toString() { return value; } /** * Use this in place of valueOf. * * @param value real value * @return S3ResourceType corresponding to the value * @throws IllegalArgumentException If the specified value does not map to one of the known values in this enum. */ public static S3ControlResourceType fromValue(String value) { if (value == null || "".equals(value)) { throw new IllegalArgumentException("Value cannot be null or empty!"); } for (S3ControlResourceType enumEntry : S3ControlResourceType.values()) { if (enumEntry.toString().equals(value)) { return enumEntry; } } throw new IllegalArgumentException("Cannot create enum from " + value + " value!"); } }
4,675
0
Create_ds/aws-sdk-java-v2/services/s3control/src/main/java/software/amazon/awssdk/services/s3control
Create_ds/aws-sdk-java-v2/services/s3control/src/main/java/software/amazon/awssdk/services/s3control/internal/HandlerUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3control.internal; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.services.s3control.S3ControlConfiguration; import software.amazon.awssdk.utils.StringUtils; @SdkInternalApi public final class HandlerUtils { public static final String X_AMZ_ACCOUNT_ID = "x-amz-account-id"; public static final String ENDPOINT_PREFIX = "s3-control"; public static final String S3_OUTPOSTS = "s3-outposts"; private HandlerUtils() { } public static boolean isDualstackEnabled(S3ControlConfiguration configuration) { return configuration != null && configuration.dualstackEnabled(); } public static boolean isFipsEnabledInClientConfig(S3ControlConfiguration configuration) { return configuration != null && configuration.fipsModeEnabled(); } public static boolean isUseArnRegionEnabledInClientConfig(S3ControlConfiguration configuration) { return configuration != null && configuration.useArnRegionEnabled(); } /** * Returns whether a FIPS pseudo region is provided. */ public static boolean isFipsRegion(String clientRegion, String arnRegion, S3ControlConfiguration serviceConfig, boolean useArnRegion) { if (useArnRegion) { return isFipsRegion(arnRegion); } return isFipsRegion(clientRegion); } /** * Returns whether a region is a FIPS pseudo region. */ public static boolean isFipsRegion(String regionName) { if (StringUtils.isEmpty(regionName)) { return false; } return regionName.startsWith("fips-") || regionName.endsWith("-fips"); } }
4,676
0
Create_ds/aws-sdk-java-v2/services/s3control/src/main/java/software/amazon/awssdk/services/s3control
Create_ds/aws-sdk-java-v2/services/s3control/src/main/java/software/amazon/awssdk/services/s3control/internal/S3ControlInternalExecutionAttribute.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3control.internal; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.interceptor.ExecutionAttribute; import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute; @SdkInternalApi public final class S3ControlInternalExecutionAttribute extends SdkExecutionAttribute { /** * The optional value contains metadata for a request with a field that contains an ARN */ public static final ExecutionAttribute<S3ArnableField> S3_ARNABLE_FIELD = new ExecutionAttribute<>("S3_ARNABLE_FIELD"); }
4,677
0
Create_ds/aws-sdk-java-v2/services/s3control/src/main/java/software/amazon/awssdk/services/s3control
Create_ds/aws-sdk-java-v2/services/s3control/src/main/java/software/amazon/awssdk/services/s3control/internal/S3ArnableField.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3control.internal; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.arns.Arn; /** * Indicating a field that can be an ARN */ @SdkInternalApi public final class S3ArnableField { private final Arn arn; private S3ArnableField(Builder builder) { this.arn = builder.arn; } public static Builder builder() { return new Builder(); } /** * @return the ARN */ public Arn arn() { return arn; } public static final class Builder { private Arn arn; private Builder() { } /** * Sets the arn * * @param arn The new arn value. * @return This object for method chaining. */ public Builder arn(Arn arn) { this.arn = arn; return this; } public S3ArnableField build() { return new S3ArnableField(this); } } }
4,678
0
Create_ds/aws-sdk-java-v2/services/s3control/src/main/java/software/amazon/awssdk/services/s3control/internal
Create_ds/aws-sdk-java-v2/services/s3control/src/main/java/software/amazon/awssdk/services/s3control/internal/interceptors/ConfigureSignerInterceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3control.internal.interceptors; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; /** * Don't double-url-encode or normalize path elements for S3, as per * https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html */ @SdkInternalApi public final class ConfigureSignerInterceptor implements ExecutionInterceptor { @Override public void beforeExecution(Context.BeforeExecution context, ExecutionAttributes executionAttributes) { executionAttributes.putAttribute(AwsSignerExecutionAttribute.SIGNER_DOUBLE_URL_ENCODE, Boolean.FALSE); executionAttributes.putAttribute(AwsSignerExecutionAttribute.SIGNER_NORMALIZE_PATH, Boolean.FALSE); } }
4,679
0
Create_ds/aws-sdk-java-v2/services/s3control/src/main/java/software/amazon/awssdk/services/s3control/internal
Create_ds/aws-sdk-java-v2/services/s3control/src/main/java/software/amazon/awssdk/services/s3control/internal/interceptors/PayloadSigningInterceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3control.internal.interceptors; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.auth.signer.S3SignerExecutionAttribute; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.http.SdkHttpMethod; /** * Turns on payload signing and prevents moving query params to body during a POST which S3 doesn't like. */ @SdkInternalApi public class PayloadSigningInterceptor implements ExecutionInterceptor { @Override public Optional<RequestBody> modifyHttpContent(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { executionAttributes.putAttribute(S3SignerExecutionAttribute.ENABLE_PAYLOAD_SIGNING, true); if (!context.requestBody().isPresent() && context.httpRequest().method() == SdkHttpMethod.POST) { return Optional.of(RequestBody.fromBytes(new byte[0])); } return context.requestBody(); } }
4,680
0
Create_ds/aws-sdk-java-v2/services/codecatalyst/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/codecatalyst/src/test/java/software/amazon/awssdk/services/codecatalyst/BearerCredentialTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.codecatalyst; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import software.amazon.awssdk.auth.token.credentials.StaticTokenProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase; import software.amazon.awssdk.testutils.service.http.MockAsyncHttpClient; import software.amazon.awssdk.testutils.service.http.MockSyncHttpClient; public class BearerCredentialTest extends AwsIntegrationTestBase { @Test public void syncClientSendsBearerToken() { try (MockSyncHttpClient httpClient = new MockSyncHttpClient(); CodeCatalystClient codeCatalyst = CodeCatalystClient.builder() .region(Region.US_WEST_2) .tokenProvider(StaticTokenProvider.create(() -> "foo-token")) .httpClient(httpClient) .build()) { httpClient.stubNextResponse200(); codeCatalyst.listSpaces(r -> {}); assertThat(httpClient.getLastRequest().firstMatchingHeader("Authorization")) .hasValue("Bearer foo-token"); } } @Test public void asyncClientSendsBearerToken() { try (MockAsyncHttpClient httpClient = new MockAsyncHttpClient(); CodeCatalystAsyncClient codeCatalyst = CodeCatalystAsyncClient.builder() .region(Region.US_WEST_2) .tokenProvider(StaticTokenProvider.create(() -> "foo-token")) .httpClient(httpClient) .build()) { httpClient.stubNextResponse200(); codeCatalyst.listSpaces(r -> {}).join(); assertThat(httpClient.getLastRequest().firstMatchingHeader("Authorization")) .hasValue("Bearer foo-token"); } } }
4,681
0
Create_ds/aws-sdk-java-v2/services/cloudfront/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/cloudfront/src/test/java/software/amazon/awssdk/services/cloudfront/CloudFrontUtilitiesTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.cloudfront; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.File; import java.io.FileWriter; import java.nio.file.Path; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.time.LocalDate; import java.time.Instant; import java.time.ZoneOffset; import java.util.Base64; 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.services.cloudfront.cookie.CookiesForCannedPolicy; import software.amazon.awssdk.services.cloudfront.cookie.CookiesForCustomPolicy; import software.amazon.awssdk.services.cloudfront.model.CannedSignerRequest; import software.amazon.awssdk.services.cloudfront.model.CustomSignerRequest; import software.amazon.awssdk.services.cloudfront.url.SignedUrl; class CloudFrontUtilitiesTest { private static final String resourceUrl = "https://d1npcfkc2mojrf.cloudfront.net/s3ObjectKey"; private static KeyPairGenerator kpg; private static KeyPair keyPair; private static File keyFile; private static Path keyFilePath; private static CloudFrontUtilities cloudFrontUtilities; @BeforeAll static void setUp() throws Exception { initKeys(); cloudFrontUtilities = CloudFrontUtilities.create(); } @AfterAll static void tearDown() { keyFile.deleteOnExit(); } static void initKeys() throws Exception { kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(2048); keyPair = kpg.generateKeyPair(); Base64.Encoder encoder = Base64.getEncoder(); keyFile = new File("key.pem"); FileWriter writer = new FileWriter(keyFile); writer.write("-----BEGIN PRIVATE KEY-----\n"); writer.write(encoder.encodeToString(keyPair.getPrivate().getEncoded())); writer.write("\n-----END PRIVATE KEY-----\n"); writer.close(); keyFilePath = keyFile.toPath(); } @Test void getSignedURLWithCannedPolicy_producesValidUrl() { Instant expirationDate = LocalDate.of(2024, 1, 1).atStartOfDay().toInstant(ZoneOffset.of("Z")); SignedUrl signedUrl = cloudFrontUtilities.getSignedUrlWithCannedPolicy(r -> r .resourceUrl(resourceUrl) .privateKey(keyPair.getPrivate()) .keyPairId("keyPairId") .expirationDate(expirationDate)); String url = signedUrl.url(); String signature = url.substring(url.indexOf("&Signature"), url.indexOf("&Key-Pair-Id")); String expected = "https://d1npcfkc2mojrf.cloudfront.net/s3ObjectKey?Expires=1704067200" + signature + "&Key-Pair-Id=keyPairId"; assertThat(expected).isEqualTo(url); } @Test void getSignedURLWithCannedPolicy_withQueryParams_producesValidUrl() { Instant expirationDate = LocalDate.of(2024, 1, 1).atStartOfDay().toInstant(ZoneOffset.of("Z")); String resourceUrlWithQueryParams = "https://d1npcfkc2mojrf.cloudfront.net/s3ObjectKey?a=b&c=d"; SignedUrl signedUrl = cloudFrontUtilities.getSignedUrlWithCannedPolicy(r -> r .resourceUrl(resourceUrlWithQueryParams) .privateKey(keyPair.getPrivate()) .keyPairId("keyPairId") .expirationDate(expirationDate)); String url = signedUrl.url(); String signature = url.substring(url.indexOf("&Signature"), url.indexOf("&Key-Pair-Id")); String expected = "https://d1npcfkc2mojrf.cloudfront.net/s3ObjectKey?a=b&c=d&Expires=1704067200" + signature + "&Key-Pair-Id=keyPairId"; assertThat(expected).isEqualTo(url); } @Test void getSignedURLWithCustomPolicy_producesValidUrl() throws Exception { Instant activeDate = LocalDate.of(2022, 1, 1).atStartOfDay().toInstant(ZoneOffset.of("Z")); Instant expirationDate = LocalDate.of(2024, 1, 1).atStartOfDay().toInstant(ZoneOffset.of("Z")); String ipRange = "1.2.3.4"; SignedUrl signedUrl = cloudFrontUtilities.getSignedUrlWithCustomPolicy(r -> { try { r.resourceUrl(resourceUrl) .privateKey(keyFilePath) .keyPairId("keyPairId") .expirationDate(expirationDate) .activeDate(activeDate) .ipRange(ipRange); } catch (Exception e) { throw new RuntimeException(e); } }); String url = signedUrl.url(); String policy = url.substring(url.indexOf("Policy=") + 7, url.indexOf("&Signature")); String signature = url.substring(url.indexOf("&Signature"), url.indexOf("&Key-Pair-Id")); String expected = "https://d1npcfkc2mojrf.cloudfront.net/s3ObjectKey?Policy=" + policy + signature + "&Key-Pair-Id=keyPairId"; assertThat(expected).isEqualTo(url); } @Test void getSignedURLWithCustomPolicy_withQueryParams_producesValidUrl() { Instant activeDate = LocalDate.of(2022, 1, 1).atStartOfDay().toInstant(ZoneOffset.of("Z")); Instant expirationDate = LocalDate.of(2024, 1, 1).atStartOfDay().toInstant(ZoneOffset.of("Z")); String ipRange = "1.2.3.4"; String resourceUrlWithQueryParams = "https://d1npcfkc2mojrf.cloudfront.net/s3ObjectKey?a=b&c=d"; SignedUrl signedUrl = cloudFrontUtilities.getSignedUrlWithCustomPolicy(r -> r .resourceUrl(resourceUrlWithQueryParams) .privateKey(keyPair.getPrivate()) .keyPairId("keyPairId") .expirationDate(expirationDate) .activeDate(activeDate) .ipRange(ipRange)); String url = signedUrl.url(); String policy = url.substring(url.indexOf("Policy=") + 7, url.indexOf("&Signature")); String signature = url.substring(url.indexOf("&Signature"), url.indexOf("&Key-Pair-Id")); String expected = "https://d1npcfkc2mojrf.cloudfront.net/s3ObjectKey?a=b&c=d&Policy=" + policy + signature + "&Key-Pair-Id=keyPairId"; assertThat(expected).isEqualTo(url); } @Test void getSignedURLWithCustomPolicy_withIpRangeOmitted_producesValidUrl() throws Exception { Instant activeDate = LocalDate.of(2022, 1, 1).atStartOfDay().toInstant(ZoneOffset.of("Z")); Instant expirationDate = LocalDate.of(2024, 1, 1).atStartOfDay().toInstant(ZoneOffset.of("Z")); CustomSignerRequest request = CustomSignerRequest.builder() .resourceUrl(resourceUrl) .privateKey(keyFilePath) .keyPairId("keyPairId") .expirationDate(expirationDate) .activeDate(activeDate) .build(); SignedUrl signedUrl = cloudFrontUtilities.getSignedUrlWithCustomPolicy(request); String url = signedUrl.url(); String policy = url.substring(url.indexOf("Policy=") + 7, url.indexOf("&Signature")); String signature = url.substring(url.indexOf("&Signature"), url.indexOf("&Key-Pair-Id")); String expected = "https://d1npcfkc2mojrf.cloudfront.net/s3ObjectKey?Policy=" + policy + signature + "&Key-Pair-Id=keyPairId"; assertThat(expected).isEqualTo(url); } @Test void getSignedURLWithCustomPolicy_withActiveDateOmitted_producesValidUrl() throws Exception { Instant expirationDate = LocalDate.of(2024, 1, 1).atStartOfDay().toInstant(ZoneOffset.of("Z")); String ipRange = "1.2.3.4"; CustomSignerRequest request = CustomSignerRequest.builder() .resourceUrl(resourceUrl) .privateKey(keyFilePath) .keyPairId("keyPairId") .expirationDate(expirationDate) .ipRange(ipRange) .build(); SignedUrl signedUrl = cloudFrontUtilities.getSignedUrlWithCustomPolicy(request); String url = signedUrl.url(); String policy = url.substring(url.indexOf("Policy=") + 7, url.indexOf("&Signature")); String signature = url.substring(url.indexOf("&Signature"), url.indexOf("&Key-Pair-Id")); String expected = "https://d1npcfkc2mojrf.cloudfront.net/s3ObjectKey?Policy=" + policy + signature + "&Key-Pair-Id=keyPairId"; assertThat(expected).isEqualTo(url); } @Test void getSignedURLWithCustomPolicy_withMissingExpirationDate_shouldThrowException() { SdkClientException exception = assertThrows(SdkClientException.class, () -> cloudFrontUtilities.getSignedUrlWithCustomPolicy(r -> r .resourceUrl(resourceUrl) .privateKey(keyPair.getPrivate()) .keyPairId("keyPairId")) ); assertThat(exception.getMessage().contains("Expiration date must be provided to sign CloudFront URLs")); } @Test void getSignedURLWithCannedPolicy_withEncodedUrl_doesNotDecodeUrl() { String encodedUrl = "https://distributionDomain/s3ObjectKey/%40blob?v=1n1dm%2F01n1dm0"; Instant expirationDate = LocalDate.of(2024, 1, 1).atStartOfDay().toInstant(ZoneOffset.of("Z")); SignedUrl signedUrl = cloudFrontUtilities.getSignedUrlWithCannedPolicy(r -> r .resourceUrl(encodedUrl) .privateKey(keyPair.getPrivate()) .keyPairId("keyPairId") .expirationDate(expirationDate)); String url = signedUrl.url(); String signature = url.substring(url.indexOf("&Signature"), url.indexOf("&Key-Pair-Id")); String expected = "https://distributionDomain/s3ObjectKey/%40blob?v=1n1dm%2F01n1dm0&Expires=1704067200" + signature + "&Key-Pair-Id=keyPairId"; assertThat(expected).isEqualTo(url); } @Test void getSignedURLWithCustomPolicy_withEncodedUrl_doesNotDecodeUrl() { String encodedUrl = "https://distributionDomain/s3ObjectKey/%40blob?v=1n1dm%2F01n1dm0"; Instant activeDate = LocalDate.of(2022, 1, 1).atStartOfDay().toInstant(ZoneOffset.of("Z")); Instant expirationDate = LocalDate.of(2024, 1, 1).atStartOfDay().toInstant(ZoneOffset.of("Z")); String ipRange = "1.2.3.4"; SignedUrl signedUrl = cloudFrontUtilities.getSignedUrlWithCustomPolicy(r -> { try { r.resourceUrl(encodedUrl) .privateKey(keyFilePath) .keyPairId("keyPairId") .expirationDate(expirationDate) .activeDate(activeDate) .ipRange(ipRange); } catch (Exception e) { throw new RuntimeException(e); } }); String url = signedUrl.url(); String policy = url.substring(url.indexOf("Policy=") + 7, url.indexOf("&Signature")); String signature = url.substring(url.indexOf("&Signature"), url.indexOf("&Key-Pair-Id")); String expected = "https://distributionDomain/s3ObjectKey/%40blob?v=1n1dm%2F01n1dm0&Policy=" + policy + signature + "&Key-Pair-Id=keyPairId"; assertThat(expected).isEqualTo(url); } @Test void getCookiesForCannedPolicy_producesValidCookies() throws Exception { Instant expirationDate = LocalDate.of(2024, 1, 1).atStartOfDay().toInstant(ZoneOffset.of("Z")); CannedSignerRequest request = CannedSignerRequest.builder() .resourceUrl(resourceUrl) .privateKey(keyFilePath) .keyPairId("keyPairId") .expirationDate(expirationDate) .build(); CookiesForCannedPolicy cookiesForCannedPolicy = cloudFrontUtilities.getCookiesForCannedPolicy(request); assertThat(cookiesForCannedPolicy.resourceUrl()).isEqualTo(resourceUrl); assertThat(cookiesForCannedPolicy.keyPairIdHeaderValue()).isEqualTo("CloudFront-Key-Pair-Id=keyPairId"); } @Test void getCookiesForCustomPolicy_producesValidCookies() throws Exception { Instant activeDate = LocalDate.of(2022, 1, 1).atStartOfDay().toInstant(ZoneOffset.of("Z")); Instant expirationDate = LocalDate.of(2024, 1, 1).atStartOfDay().toInstant(ZoneOffset.of("Z")); String ipRange = "1.2.3.4"; CustomSignerRequest request = CustomSignerRequest.builder() .resourceUrl(resourceUrl) .privateKey(keyFilePath) .keyPairId("keyPairId") .expirationDate(expirationDate) .activeDate(activeDate) .ipRange(ipRange) .build(); CookiesForCustomPolicy cookiesForCustomPolicy = cloudFrontUtilities.getCookiesForCustomPolicy(request); assertThat(cookiesForCustomPolicy.resourceUrl()).isEqualTo(resourceUrl); assertThat(cookiesForCustomPolicy.keyPairIdHeaderValue()).isEqualTo("CloudFront-Key-Pair-Id=keyPairId"); } @Test void getCookiesForCustomPolicy_withActiveDateAndIpRangeOmitted_producesValidCookies() { Instant expirationDate = LocalDate.of(2024, 1, 1).atStartOfDay().toInstant(ZoneOffset.of("Z")); CustomSignerRequest request = CustomSignerRequest.builder() .resourceUrl(resourceUrl) .privateKey(keyPair.getPrivate()) .keyPairId("keyPairId") .expirationDate(expirationDate) .build(); CookiesForCustomPolicy cookiesForCustomPolicy = cloudFrontUtilities.getCookiesForCustomPolicy(request); assertThat(cookiesForCustomPolicy.resourceUrl()).isEqualTo(resourceUrl); assertThat(cookiesForCustomPolicy.keyPairIdHeaderValue()).isEqualTo("CloudFront-Key-Pair-Id=keyPairId"); } }
4,682
0
Create_ds/aws-sdk-java-v2/services/cloudfront/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/cloudfront/src/test/java/software/amazon/awssdk/services/cloudfront/CloudFrontUtilitiesIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.cloudfront; import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.nio.file.Path; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.time.Instant; import java.time.LocalDate; import java.time.ZoneOffset; import java.util.Base64; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.http.HttpExecuteRequest; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.apache.ApacheHttpClient; import software.amazon.awssdk.services.cloudfront.cookie.CookiesForCannedPolicy; import software.amazon.awssdk.services.cloudfront.cookie.CookiesForCustomPolicy; import software.amazon.awssdk.services.cloudfront.url.SignedUrl; import software.amazon.awssdk.services.cloudfront.model.Aliases; import software.amazon.awssdk.services.cloudfront.model.CacheBehavior; import software.amazon.awssdk.services.cloudfront.model.CacheBehaviors; import software.amazon.awssdk.services.cloudfront.model.CannedSignerRequest; import software.amazon.awssdk.services.cloudfront.model.CloudFrontOriginAccessIdentityConfig; import software.amazon.awssdk.services.cloudfront.model.CookiePreference; import software.amazon.awssdk.services.cloudfront.model.CreateCloudFrontOriginAccessIdentityRequest; import software.amazon.awssdk.services.cloudfront.model.CreateCloudFrontOriginAccessIdentityResponse; import software.amazon.awssdk.services.cloudfront.model.CreateDistributionRequest; import software.amazon.awssdk.services.cloudfront.model.CreateDistributionResponse; import software.amazon.awssdk.services.cloudfront.model.CreateKeyGroupRequest; import software.amazon.awssdk.services.cloudfront.model.CreatePublicKeyRequest; import software.amazon.awssdk.services.cloudfront.model.CreatePublicKeyResponse; import software.amazon.awssdk.services.cloudfront.model.CustomSignerRequest; import software.amazon.awssdk.services.cloudfront.model.DefaultCacheBehavior; import software.amazon.awssdk.services.cloudfront.model.DeleteCloudFrontOriginAccessIdentityRequest; import software.amazon.awssdk.services.cloudfront.model.DeleteDistributionRequest; import software.amazon.awssdk.services.cloudfront.model.DeleteKeyGroupRequest; import software.amazon.awssdk.services.cloudfront.model.DeletePublicKeyRequest; import software.amazon.awssdk.services.cloudfront.model.DistributionConfig; import software.amazon.awssdk.services.cloudfront.model.ForwardedValues; import software.amazon.awssdk.services.cloudfront.model.GetCloudFrontOriginAccessIdentityRequest; import software.amazon.awssdk.services.cloudfront.model.GetDistributionConfigRequest; import software.amazon.awssdk.services.cloudfront.model.GetDistributionConfigResponse; import software.amazon.awssdk.services.cloudfront.model.GetKeyGroupRequest; import software.amazon.awssdk.services.cloudfront.model.GetPublicKeyRequest; import software.amazon.awssdk.services.cloudfront.model.Headers; import software.amazon.awssdk.services.cloudfront.model.KeyGroup; import software.amazon.awssdk.services.cloudfront.model.KeyGroupConfig; import software.amazon.awssdk.services.cloudfront.model.LoggingConfig; import software.amazon.awssdk.services.cloudfront.model.Origin; import software.amazon.awssdk.services.cloudfront.model.Origins; import software.amazon.awssdk.services.cloudfront.model.PriceClass; import software.amazon.awssdk.services.cloudfront.model.PublicKeyConfig; import software.amazon.awssdk.services.cloudfront.model.S3OriginConfig; import software.amazon.awssdk.services.cloudfront.model.TrustedKeyGroups; import software.amazon.awssdk.services.cloudfront.model.UpdateDistributionResponse; import software.amazon.awssdk.services.cloudfront.model.ViewerProtocolPolicy; import software.amazon.awssdk.services.s3.model.CreateBucketRequest; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.s3.model.PutBucketPolicyRequest; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.testutils.RandomTempFile; import software.amazon.awssdk.testutils.service.S3BucketUtils; public class CloudFrontUtilitiesIntegrationTest extends IntegrationTestBase { private static final Base64.Encoder encoder = Base64.getEncoder(); private static final String callerReference = S3BucketUtils.temporaryBucketName(String.valueOf(Instant.now().getEpochSecond())); private static final String s3ObjectKey = "s3ObjectKey"; private static String domainName; private static String resourceUrl; private static String keyPairId; private static KeyPair keyPair; private static File keyFile; private static Path keyFilePath; private static String keyGroupId; private static String originAccessId; private static String distributionId; private static String distributionETag; @BeforeAll public static void init() throws Exception { IntegrationTestBase.setUp(); initKeys(); setUpDistribution(); } @AfterAll public static void tearDown() throws Exception { disableDistribution(); cloudFrontClient.deleteDistribution(DeleteDistributionRequest.builder().ifMatch(distributionETag).id(distributionId).build()); deleteBucketAndAllContents(callerReference); String keyGroupETag = cloudFrontClient.getKeyGroup(GetKeyGroupRequest.builder().id(keyGroupId).build()).eTag(); cloudFrontClient.deleteKeyGroup(DeleteKeyGroupRequest.builder().ifMatch(keyGroupETag).id(keyGroupId).build()); String publicKeyETag = cloudFrontClient.getPublicKey(GetPublicKeyRequest.builder().id(keyPairId).build()).eTag(); cloudFrontClient.deletePublicKey(DeletePublicKeyRequest.builder().ifMatch(publicKeyETag).id(keyPairId).build()); String originAccessIdETag = cloudFrontClient.getCloudFrontOriginAccessIdentity(GetCloudFrontOriginAccessIdentityRequest .builder().id(originAccessId).build()).eTag(); cloudFrontClient.deleteCloudFrontOriginAccessIdentity(DeleteCloudFrontOriginAccessIdentityRequest .builder().ifMatch(originAccessIdETag).id(originAccessId).build()); keyFile.deleteOnExit(); } @Test void unsignedUrl_shouldReturn403Response() throws Exception { SdkHttpClient client = ApacheHttpClient.create(); HttpExecuteResponse response = client.prepareRequest(HttpExecuteRequest.builder() .request(SdkHttpRequest.builder() .encodedPath(resourceUrl) .host(domainName) .method(SdkHttpMethod.GET) .protocol("https") .build()) .build()).call(); int expectedStatus = 403; assertThat(response.httpResponse().statusCode()).isEqualTo(expectedStatus); } @Test void getSignedUrlWithCannedPolicy_producesValidUrl() throws Exception { InputStream originalBucketContent = s3Client.getObject(GetObjectRequest.builder().bucket(callerReference).key(s3ObjectKey).build()); Instant expirationDate = LocalDate.of(2050, 1, 1).atStartOfDay().toInstant(ZoneOffset.of("Z")); CannedSignerRequest request = CannedSignerRequest.builder() .resourceUrl(resourceUrl) .privateKey(keyFilePath) .keyPairId(keyPairId) .expirationDate(expirationDate).build(); SignedUrl signedUrl = cloudFrontUtilities.getSignedUrlWithCannedPolicy(request); SdkHttpClient client = ApacheHttpClient.create(); HttpExecuteResponse response = client.prepareRequest(HttpExecuteRequest.builder() .request(signedUrl.createHttpGetRequest()) .build()).call(); int expectedStatus = 200; assertThat(response.httpResponse().statusCode()).isEqualTo(expectedStatus); InputStream retrievedBucketContent = response.responseBody().get(); assertThat(retrievedBucketContent).hasSameContentAs(originalBucketContent); } @Test void getSignedUrlWithCannedPolicy_withExpiredDate_shouldReturn403Response() throws Exception { Instant expirationDate = LocalDate.of(2020, 1, 1).atStartOfDay().toInstant(ZoneOffset.of("Z")); SignedUrl signedUrl = cloudFrontUtilities.getSignedUrlWithCannedPolicy(r -> r.resourceUrl(resourceUrl) .privateKey(keyPair.getPrivate()) .keyPairId(keyPairId) .expirationDate(expirationDate)); SdkHttpClient client = ApacheHttpClient.create(); HttpExecuteResponse response = client.prepareRequest(HttpExecuteRequest.builder() .request(signedUrl.createHttpGetRequest()) .build()).call(); int expectedStatus = 403; assertThat(response.httpResponse().statusCode()).isEqualTo(expectedStatus); } @Test void getSignedUrlWithCustomPolicy_producesValidUrl() throws Exception { InputStream originalBucketContent = s3Client.getObject(GetObjectRequest.builder().bucket(callerReference).key(s3ObjectKey).build()); Instant activeDate = LocalDate.of(2022, 1, 1).atStartOfDay().toInstant(ZoneOffset.of("Z")); Instant expirationDate = LocalDate.of(2050, 1, 1).atStartOfDay().toInstant(ZoneOffset.of("Z")); CustomSignerRequest request = CustomSignerRequest.builder() .resourceUrl(resourceUrl) .privateKey(keyFilePath) .keyPairId(keyPairId) .expirationDate(expirationDate) .activeDate(activeDate).build(); SignedUrl signedUrl = cloudFrontUtilities.getSignedUrlWithCustomPolicy(request); SdkHttpClient client = ApacheHttpClient.create(); HttpExecuteResponse response = client.prepareRequest(HttpExecuteRequest.builder() .request(signedUrl.createHttpGetRequest()) .build()).call(); int expectedStatus = 200; assertThat(response.httpResponse().statusCode()).isEqualTo(expectedStatus); InputStream retrievedBucketContent = response.responseBody().get(); assertThat(retrievedBucketContent).hasSameContentAs(originalBucketContent); } @Test void getSignedUrlWithCustomPolicy_withFutureActiveDate_shouldReturn403Response() throws Exception { Instant activeDate = LocalDate.of(2040, 1, 1).atStartOfDay().toInstant(ZoneOffset.of("Z")); Instant expirationDate = LocalDate.of(2050, 1, 1).atStartOfDay().toInstant(ZoneOffset.of("Z")); SignedUrl signedUrl = cloudFrontUtilities.getSignedUrlWithCustomPolicy(r -> r.resourceUrl(resourceUrl) .privateKey(keyPair.getPrivate()) .keyPairId(keyPairId) .expirationDate(expirationDate) .activeDate(activeDate)); SdkHttpClient client = ApacheHttpClient.create(); HttpExecuteResponse response = client.prepareRequest(HttpExecuteRequest.builder() .request(signedUrl.createHttpGetRequest()) .build()).call(); int expectedStatus = 403; assertThat(response.httpResponse().statusCode()).isEqualTo(expectedStatus); } @Test void getCookiesForCannedPolicy_producesValidCookies() throws Exception { InputStream originalBucketContent = s3Client.getObject(GetObjectRequest.builder().bucket(callerReference).key(s3ObjectKey).build()); Instant expirationDate = LocalDate.of(2050, 1, 1).atStartOfDay().toInstant(ZoneOffset.of("Z")); CookiesForCannedPolicy cookies = cloudFrontUtilities.getCookiesForCannedPolicy(r -> r.resourceUrl(resourceUrl) .privateKey(keyPair.getPrivate()) .keyPairId(keyPairId) .expirationDate(expirationDate)); SdkHttpClient client = ApacheHttpClient.create(); HttpExecuteResponse response = client.prepareRequest(HttpExecuteRequest.builder() .request(cookies.createHttpGetRequest()) .build()).call(); int expectedStatus = 200; assertThat(response.httpResponse().statusCode()).isEqualTo(expectedStatus); InputStream retrievedBucketContent = response.responseBody().get(); assertThat(retrievedBucketContent).hasSameContentAs(originalBucketContent); } @Test void getCookiesForCannedPolicy_withExpiredDate_shouldReturn403Response() throws Exception { Instant expirationDate = LocalDate.of(2020, 1, 1).atStartOfDay().toInstant(ZoneOffset.of("Z")); CannedSignerRequest request = CannedSignerRequest.builder() .resourceUrl(resourceUrl) .privateKey(keyFilePath) .keyPairId(keyPairId) .expirationDate(expirationDate).build(); CookiesForCannedPolicy cookies = cloudFrontUtilities.getCookiesForCannedPolicy(request); SdkHttpClient client = ApacheHttpClient.create(); HttpExecuteResponse response = client.prepareRequest(HttpExecuteRequest.builder() .request(cookies.createHttpGetRequest()) .build()).call(); int expectedStatus = 403; assertThat(response.httpResponse().statusCode()).isEqualTo(expectedStatus); } @Test void getCookiesForCustomPolicy_producesValidCookies() throws Exception { InputStream originalBucketContent = s3Client.getObject(GetObjectRequest.builder().bucket(callerReference).key(s3ObjectKey).build()); Instant activeDate = LocalDate.of(2022, 1, 1).atStartOfDay().toInstant(ZoneOffset.of("Z")); Instant expirationDate = LocalDate.of(2050, 1, 1).atStartOfDay().toInstant(ZoneOffset.of("Z")); CookiesForCustomPolicy cookies = cloudFrontUtilities.getCookiesForCustomPolicy(r -> r.resourceUrl(resourceUrl) .privateKey(keyPair.getPrivate()) .keyPairId(keyPairId) .expirationDate(expirationDate) .activeDate(activeDate)); SdkHttpClient client = ApacheHttpClient.create(); HttpExecuteResponse response = client.prepareRequest(HttpExecuteRequest.builder() .request(cookies.createHttpGetRequest()) .build()).call(); int expectedStatus = 200; assertThat(response.httpResponse().statusCode()).isEqualTo(expectedStatus); InputStream retrievedBucketContent = response.responseBody().get(); assertThat(retrievedBucketContent).hasSameContentAs(originalBucketContent); } @Test void getCookiesForCustomPolicy_withFutureActiveDate_shouldReturn403Response() throws Exception { Instant activeDate = LocalDate.of(2040, 1, 1).atStartOfDay().toInstant(ZoneOffset.of("Z")); Instant expirationDate = LocalDate.of(2050, 1, 1).atStartOfDay().toInstant(ZoneOffset.of("Z")); CustomSignerRequest request = CustomSignerRequest.builder() .resourceUrl(resourceUrl) .privateKey(keyFilePath) .keyPairId(keyPairId) .expirationDate(expirationDate) .activeDate(activeDate).build(); CookiesForCustomPolicy cookies = cloudFrontUtilities.getCookiesForCustomPolicy(request); SdkHttpClient client = ApacheHttpClient.create(); HttpExecuteResponse response = client.prepareRequest(HttpExecuteRequest.builder() .request(cookies.createHttpGetRequest()) .build()).call(); int expectedStatus = 403; assertThat(response.httpResponse().statusCode()).isEqualTo(expectedStatus); } static void setUpDistribution() throws IOException, InterruptedException { CreateCloudFrontOriginAccessIdentityResponse response = cloudFrontClient.createCloudFrontOriginAccessIdentity( CreateCloudFrontOriginAccessIdentityRequest.builder() .cloudFrontOriginAccessIdentityConfig(CloudFrontOriginAccessIdentityConfig.builder() .callerReference(callerReference) .comment("SignerTestAccessIdentity" + callerReference) .build()) .build()); originAccessId = response.cloudFrontOriginAccessIdentity().id(); KeyGroup keyGroup = cloudFrontClient.createKeyGroup(CreateKeyGroupRequest.builder().keyGroupConfig(KeyGroupConfig.builder() .name("TestKeyGroup" + callerReference) .items(keyPairId) .build()).build()).keyGroup(); keyGroupId = keyGroup.id(); s3Client.createBucket(CreateBucketRequest.builder().bucket(callerReference).build()); File content = new RandomTempFile("testFile", 1000L); s3Client.putObject(PutObjectRequest.builder().bucket(callerReference).key(s3ObjectKey).build(), RequestBody.fromFile(content)); DefaultCacheBehavior defaultCacheBehavior = DefaultCacheBehavior.builder() .forwardedValues(ForwardedValues.builder() .queryString(false).cookies(CookiePreference.builder().forward("none").build()) .headers(Headers.builder().quantity(0).build()).build()).minTTL(10000L).maxTTL(10000L).defaultTTL(10000L) .targetOriginId("1") .viewerProtocolPolicy(ViewerProtocolPolicy.ALLOW_ALL) .trustedKeyGroups(TrustedKeyGroups.builder().enabled(true).quantity(1).items(keyGroup.id()).build()).build(); CacheBehavior cacheBehavior = CacheBehavior.builder() .forwardedValues(ForwardedValues.builder() .queryString(false).cookies(CookiePreference.builder().forward("none").build()) .headers(Headers.builder().quantity(0).build()).build()).minTTL(10000L).maxTTL(10000L).defaultTTL(10000L) .targetOriginId("1") .viewerProtocolPolicy(ViewerProtocolPolicy.ALLOW_ALL) .trustedKeyGroups(TrustedKeyGroups.builder().enabled(true).quantity(1).items(keyGroup.id()).build()).pathPattern("*").build(); Origin origin = Origin.builder() .domainName(callerReference + ".s3.amazonaws.com") .id("1") .s3OriginConfig(S3OriginConfig.builder().originAccessIdentity("origin-access-identity/cloudfront/" + originAccessId).build()).build(); DistributionConfig distributionConfiguration = DistributionConfig.builder() .priceClass(PriceClass.PRICE_CLASS_100) .defaultCacheBehavior(defaultCacheBehavior) .aliases(Aliases.builder().quantity(0).build()) .logging(LoggingConfig.builder() .includeCookies(false) .enabled(false) .bucket(callerReference) .prefix("").build()) .callerReference(callerReference) .cacheBehaviors(CacheBehaviors.builder() .quantity(1) .items(cacheBehavior).build()) .comment("PresignerTestDistribution") .defaultRootObject("") .enabled(true) .origins(Origins.builder() .quantity(1) .items(origin).build()).build(); CreateDistributionResponse createDistributionResponse = cloudFrontClient.createDistribution(CreateDistributionRequest.builder().distributionConfig(distributionConfiguration).build()); domainName = createDistributionResponse.distribution().domainName(); resourceUrl = "https://" + domainName + "/" + s3ObjectKey; distributionId = createDistributionResponse.distribution().id(); distributionETag = createDistributionResponse.eTag(); waitForDistributionToDeploy(distributionId); String bucketPolicy = "{\n" + "\"Version\":\"2012-10-17\",\n" + "\"Id\":\"PolicyForCloudFrontPrivateContent\",\n" + "\"Statement\":[\n" + "{\n" + "\"Effect\":\"Allow\",\n" + "\"Principal\":{\n" + "\"AWS\":\"arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity " + originAccessId + "\"\n" + "},\n" + "\"Action\":\"s3:GetObject\",\n" + "\"Resource\":\"arn:aws:s3:::" + callerReference + "/*\"\n" + "}\n" + "]\n" + "}"; s3Client.putBucketPolicy(PutBucketPolicyRequest.builder().bucket(callerReference).policy(bucketPolicy).build()); } static void initKeys() throws NoSuchAlgorithmException, IOException { KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(2048); keyPair = kpg.generateKeyPair(); keyFile = new File("src/test/key.pem"); FileWriter writer = new FileWriter(keyFile); writer.write("-----BEGIN PRIVATE KEY-----\n"); writer.write(encoder.encodeToString(keyPair.getPrivate().getEncoded())); writer.write("\n-----END PRIVATE KEY-----\n"); writer.close(); keyFilePath = keyFile.toPath(); String encodedKey = "-----BEGIN PUBLIC KEY-----\n" + encoder.encodeToString(keyPair.getPublic().getEncoded()) + "\n-----END PUBLIC KEY-----\n"; CreatePublicKeyResponse publicKeyResponse = cloudFrontClient.createPublicKey(CreatePublicKeyRequest.builder().publicKeyConfig(PublicKeyConfig.builder() .callerReference(callerReference) .name("testKey" + callerReference) .encodedKey(encodedKey).build()).build()); keyPairId = publicKeyResponse.publicKey().id(); } static void disableDistribution() throws InterruptedException { GetDistributionConfigResponse distributionConfigResponse = cloudFrontClient.getDistributionConfig(GetDistributionConfigRequest.builder().id(distributionId).build()); distributionETag = distributionConfigResponse.eTag(); DistributionConfig originalConfig = distributionConfigResponse.distributionConfig(); UpdateDistributionResponse updateDistributionResponse = cloudFrontClient.updateDistribution(r -> r.id(distributionId) .ifMatch(distributionETag) .distributionConfig(originalConfig.toBuilder() .enabled(false) .build())); distributionETag = updateDistributionResponse.eTag(); waitForDistributionToDeploy(distributionId); } }
4,683
0
Create_ds/aws-sdk-java-v2/services/cloudfront/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/cloudfront/src/test/java/software/amazon/awssdk/services/cloudfront/IntegrationTestBase.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.cloudfront; import org.junit.BeforeClass; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cloudfront.model.GetDistributionRequest; import software.amazon.awssdk.services.cloudfront.model.GetDistributionResponse; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.DeleteBucketRequest; import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; import software.amazon.awssdk.services.s3.model.ListObjectsRequest; import software.amazon.awssdk.services.s3.model.ListObjectsResponse; import software.amazon.awssdk.services.s3.model.S3Object; import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase; public class IntegrationTestBase extends AwsIntegrationTestBase { protected static CloudFrontClient cloudFrontClient; protected static CloudFrontUtilities cloudFrontUtilities; protected static S3Client s3Client; /** * Loads the AWS account info for the integration tests and creates an * AutoScaling client for tests to use. */ @BeforeClass public static void setUp() { cloudFrontClient = CloudFrontClient.builder() .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .region(Region.AWS_GLOBAL) .build(); cloudFrontUtilities = cloudFrontClient.utilities(); s3Client = S3Client.builder() .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .region(Region.US_EAST_1) .build(); } /** * Polls the test distribution until it moves into the "Deployed" state, or * throws an exception and gives up after waiting too long. * * @param distributionId * The distribution to delete */ protected static void waitForDistributionToDeploy(String distributionId) throws InterruptedException { int timeoutInMinutes = 20; long startTime = System.currentTimeMillis(); while (true) { GetDistributionResponse getDistributionResponse = cloudFrontClient.getDistribution(GetDistributionRequest.builder().id(distributionId).build()); String status = getDistributionResponse.distribution().status(); System.out.println(status); if (status.equalsIgnoreCase("Deployed")) { return; } if ((System.currentTimeMillis() - startTime) > (1000 * 60 * timeoutInMinutes)) { throw new RuntimeException("Waited " + timeoutInMinutes + " minutes for distribution to be deployed, but never happened"); } Thread.sleep(1000 * 20); } } /** * Deletes all objects in the specified bucket, and then deletes the bucket. * * @param bucketName * The bucket to empty and delete. */ protected static void deleteBucketAndAllContents(String bucketName) { ListObjectsResponse listObjectsResponse = s3Client.listObjects(ListObjectsRequest.builder().bucket(bucketName).build()); for (S3Object obj: listObjectsResponse.contents()) { s3Client.deleteObject(DeleteObjectRequest.builder().bucket(bucketName).key(obj.key()).build()); } s3Client.deleteBucket(DeleteBucketRequest.builder().bucket(bucketName).build()); } }
4,684
0
Create_ds/aws-sdk-java-v2/services/cloudfront/src/test/java/software/amazon/awssdk/services/cloudfront
Create_ds/aws-sdk-java-v2/services/cloudfront/src/test/java/software/amazon/awssdk/services/cloudfront/url/SignedUrlTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.cloudfront.url; import static org.assertj.core.api.Assertions.assertThat; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.services.cloudfront.internal.url.DefaultSignedUrl; class SignedUrlTest { private static final String PROTOCOL = "https"; private static final String DOMAIN = "d1npcfkc2mojrf.cloudfront.net"; private static final String ENCODED_PATH = "/encodedPath"; private static final String URL = PROTOCOL + "://" + DOMAIN + ENCODED_PATH; @Test void signedUrl_producesValidUrl() { SignedUrl signedUrl = DefaultSignedUrl.builder() .protocol(PROTOCOL). domain(DOMAIN). encodedPath(ENCODED_PATH). url(URL).build(); assertThat(signedUrl.protocol()).isEqualTo(PROTOCOL); assertThat(signedUrl.domain()).isEqualTo(DOMAIN); assertThat(signedUrl.encodedPath()).isEqualTo(ENCODED_PATH); assertThat(signedUrl.url()).isEqualTo(URL); } @Test void generateHttpGetRequest_producesValidRequest() { SignedUrl signedUrl = DefaultSignedUrl.builder() .protocol(PROTOCOL) .domain(DOMAIN) .encodedPath(ENCODED_PATH).build(); SdkHttpRequest httpRequest = signedUrl.createHttpGetRequest(); assertThat(httpRequest.protocol()).isEqualTo(PROTOCOL); assertThat(httpRequest.host()).isEqualTo(DOMAIN); assertThat(httpRequest.encodedPath()).isEqualTo(ENCODED_PATH); } @Test void testEqualsAndHashCodeContract() { EqualsVerifier.forClass(DefaultSignedUrl.class).verify(); } }
4,685
0
Create_ds/aws-sdk-java-v2/services/cloudfront/src/test/java/software/amazon/awssdk/services/cloudfront
Create_ds/aws-sdk-java-v2/services/cloudfront/src/test/java/software/amazon/awssdk/services/cloudfront/cookie/SignedCookieTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.cloudfront.cookie; import static org.assertj.core.api.Assertions.assertThat; import java.net.URI; import java.util.List; import java.util.Map; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.services.cloudfront.internal.cookie.DefaultCookiesForCannedPolicy; import software.amazon.awssdk.services.cloudfront.internal.cookie.DefaultCookiesForCustomPolicy; class SignedCookieTest { private static final String KEY_PAIR_ID_KEY = "CloudFront-Key-Pair-Id"; private static final String SIGNATURE_KEY = "CloudFront-Signature"; private static final String EXPIRES_KEY = "CloudFront-Expires"; private static final String POLICY_KEY = "CloudFront-Policy"; private static final String KEY_PAIR_ID_VALUE = "keyPairIdValue"; private static final String SIGNATURE_VALUE = "signatureValue"; private static final String EXPIRES_VALUE = "expiresValue"; private static final String POLICY_VALUE = "policyValue"; private static final String RESOURCE_URL = "https://d1npcfkc2mojrf.cloudfront.net/resourcePath"; private static final String EXPECTED_KEY_PAIR_ID_HEADER = KEY_PAIR_ID_KEY + "=" + KEY_PAIR_ID_VALUE; private static final String EXPECTED_SIGNATURE_HEADER = SIGNATURE_KEY + "=" + SIGNATURE_VALUE; private static final String EXPECTED_EXPIRES_HEADER = EXPIRES_KEY + "=" + EXPIRES_VALUE; private static final String EXPECTED_POLICY_HEADER = POLICY_KEY + "=" + POLICY_VALUE; @Test void cookiesForCannedPolicy_producesValidCookies() { CookiesForCannedPolicy cookiesForCannedPolicy = DefaultCookiesForCannedPolicy.builder() .resourceUrl(RESOURCE_URL) .keyPairIdHeaderValue(KEY_PAIR_ID_KEY + "=" + KEY_PAIR_ID_VALUE) .signatureHeaderValue(SIGNATURE_KEY + "=" + SIGNATURE_VALUE) .expiresHeaderValue(EXPIRES_KEY + "=" + EXPIRES_VALUE) .build(); assertThat(cookiesForCannedPolicy.resourceUrl()).isEqualTo(RESOURCE_URL); assertThat(cookiesForCannedPolicy.keyPairIdHeaderValue()).isEqualTo(EXPECTED_KEY_PAIR_ID_HEADER); assertThat(cookiesForCannedPolicy.signatureHeaderValue()).isEqualTo(EXPECTED_SIGNATURE_HEADER); assertThat(cookiesForCannedPolicy.expiresHeaderValue()).isEqualTo(EXPECTED_EXPIRES_HEADER); } @Test void cookiesForCustomPolicy_producesValidCookies() { CookiesForCustomPolicy cookiesForCustomPolicy = DefaultCookiesForCustomPolicy.builder() .resourceUrl(RESOURCE_URL) .keyPairIdHeaderValue(KEY_PAIR_ID_KEY + "=" + KEY_PAIR_ID_VALUE) .signatureHeaderValue(SIGNATURE_KEY + "=" + SIGNATURE_VALUE) .policyHeaderValue(POLICY_KEY + "=" + POLICY_VALUE) .build(); assertThat(cookiesForCustomPolicy.resourceUrl()).isEqualTo(RESOURCE_URL); assertThat(cookiesForCustomPolicy.keyPairIdHeaderValue()).isEqualTo(EXPECTED_KEY_PAIR_ID_HEADER); assertThat(cookiesForCustomPolicy.signatureHeaderValue()).isEqualTo(EXPECTED_SIGNATURE_HEADER); assertThat(cookiesForCustomPolicy.policyHeaderValue()).isEqualTo(EXPECTED_POLICY_HEADER); } @Test void generateHttpGetRequest_producesValidCookies() { CookiesForCannedPolicy cookiesForCannedPolicy = DefaultCookiesForCannedPolicy.builder() .resourceUrl(RESOURCE_URL) .keyPairIdHeaderValue(KEY_PAIR_ID_KEY + "=" + KEY_PAIR_ID_VALUE) .signatureHeaderValue(SIGNATURE_KEY + "=" + SIGNATURE_VALUE) .expiresHeaderValue(EXPIRES_KEY + "=" + EXPIRES_VALUE) .build(); SdkHttpRequest httpRequestCannedPolicy = cookiesForCannedPolicy.createHttpGetRequest(); Map<String, List<String>> headersCannedPolicy = httpRequestCannedPolicy.headers(); List<String> headerValuesCannedPolicy = headersCannedPolicy.get("Cookie"); assertThat(httpRequestCannedPolicy.getUri()).isEqualTo(URI.create(RESOURCE_URL)); assertThat(headerValuesCannedPolicy.get(0)).isEqualTo(EXPECTED_SIGNATURE_HEADER); assertThat(headerValuesCannedPolicy.get(1)).isEqualTo(EXPECTED_KEY_PAIR_ID_HEADER); assertThat(headerValuesCannedPolicy.get(2)).isEqualTo(EXPECTED_EXPIRES_HEADER); CookiesForCustomPolicy cookiesForCustomPolicy = DefaultCookiesForCustomPolicy.builder() .resourceUrl(RESOURCE_URL) .keyPairIdHeaderValue(KEY_PAIR_ID_KEY + "=" + KEY_PAIR_ID_VALUE) .signatureHeaderValue(SIGNATURE_KEY + "=" + SIGNATURE_VALUE) .policyHeaderValue(POLICY_KEY + "=" + POLICY_VALUE) .build(); SdkHttpRequest httpRequestCustomPolicy = cookiesForCustomPolicy.createHttpGetRequest(); Map<String, List<String>> headersCustomPolicy = httpRequestCustomPolicy.headers(); List<String> headerValuesCustomPolicy = headersCustomPolicy.get("Cookie"); assertThat(httpRequestCustomPolicy.getUri()).isEqualTo(URI.create(RESOURCE_URL)); assertThat(headerValuesCustomPolicy.get(0)).isEqualTo(EXPECTED_POLICY_HEADER); assertThat(headerValuesCustomPolicy.get(1)).isEqualTo(EXPECTED_SIGNATURE_HEADER); assertThat(headerValuesCustomPolicy.get(2)).isEqualTo(EXPECTED_KEY_PAIR_ID_HEADER); } @Test void testEqualsAndHashCodeContract() { EqualsVerifier.forClass(DefaultCookiesForCannedPolicy.class).verify(); EqualsVerifier.forClass(DefaultCookiesForCustomPolicy.class).verify(); } }
4,686
0
Create_ds/aws-sdk-java-v2/services/cloudfront/src/main/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/cloudfront/src/main/java/software/amazon/awssdk/services/cloudfront/CloudFrontUtilities.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.cloudfront; import static java.nio.charset.StandardCharsets.UTF_8; import java.net.URI; import java.security.InvalidKeyException; import java.util.function.Consumer; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.services.cloudfront.cookie.CookiesForCannedPolicy; import software.amazon.awssdk.services.cloudfront.cookie.CookiesForCustomPolicy; import software.amazon.awssdk.services.cloudfront.internal.cookie.DefaultCookiesForCannedPolicy; import software.amazon.awssdk.services.cloudfront.internal.cookie.DefaultCookiesForCustomPolicy; import software.amazon.awssdk.services.cloudfront.internal.url.DefaultSignedUrl; import software.amazon.awssdk.services.cloudfront.internal.utils.SigningUtils; import software.amazon.awssdk.services.cloudfront.model.CannedSignerRequest; import software.amazon.awssdk.services.cloudfront.model.CustomSignerRequest; import software.amazon.awssdk.services.cloudfront.url.SignedUrl; /** * * Utilities for working with CloudFront distributions * <p> * To securely serve private content by using CloudFront, you can require that users access your private content by using * special CloudFront signed URLs or signed cookies. You then develop your application either to create and distribute signed * URLs to authenticated users or to send Set-Cookie headers that set signed cookies for authenticated users. * <p> * Signed URLs take precedence over signed cookies. If you use both signed URLs and signed cookies to control access to the * same files and a viewer uses a signed URL to request a file, CloudFront determines whether to return the file to the * viewer based only on the signed URL. * */ @Immutable @ThreadSafe @SdkPublicApi public final class CloudFrontUtilities { private static final String KEY_PAIR_ID_KEY = "CloudFront-Key-Pair-Id"; private static final String SIGNATURE_KEY = "CloudFront-Signature"; private static final String EXPIRES_KEY = "CloudFront-Expires"; private static final String POLICY_KEY = "CloudFront-Policy"; private CloudFrontUtilities() { } public static CloudFrontUtilities create() { return new CloudFrontUtilities(); } /** * Returns a signed URL with a canned policy that grants universal access to * private content until a given date. * For more information, see <a href= * "https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-creating-signed-url-canned-policy.html" * >Creating a signed URL using a canned policy</a>. * * <p> * This is a convenience which creates an instance of the {@link CannedSignerRequest.Builder} avoiding the need to * create one manually via {@link CannedSignerRequest#builder()} * * @param request * A {@link Consumer} that will call methods on {@link CannedSignerRequest.Builder} to create a request. * @return A signed URL that will permit access to a specific distribution * and S3 object. * * <p><b>Example Usage</b> * <p> * {@snippet : * //Generates signed URL String with canned policy, valid for 7 days * CloudFrontUtilities utilities = CloudFrontUtilities.create(); * * Instant expirationDate = Instant.now().plus(Duration.ofDays(7)); * String resourceUrl = "https://d111111abcdef8.cloudfront.net/s3ObjectKey"; * String keyPairId = "myKeyPairId"; * PrivateKey privateKey = myPrivateKey; * * SignedUrl signedUrl = utilities.getSignedUrlWithCannedPolicy(r -> r.resourceUrl(resourceUrl) * .privateKey(privateKey) * .keyPairId(keyPairId) * .expirationDate(expirationDate)); * String url = signedUrl.url(); * } */ public SignedUrl getSignedUrlWithCannedPolicy(Consumer<CannedSignerRequest.Builder> request) { return getSignedUrlWithCannedPolicy(CannedSignerRequest.builder().applyMutation(request).build()); } /** * Returns a signed URL with a canned policy that grants universal access to * private content until a given date. * For more information, see <a href= * "https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-creating-signed-url-canned-policy.html" * >Creating a signed URL using a canned policy</a>. * * @param request * A {@link CannedSignerRequest} configured with the following values: * resourceUrl, privateKey, keyPairId, expirationDate * @return A signed URL that will permit access to a specific distribution * and S3 object. * * <p><b>Example Usage</b> * <p> * {@snippet : * //Generates signed URL String with canned policy, valid for 7 days * CloudFrontUtilities utilities = CloudFrontUtilities.create(); * * Instant expirationDate = Instant.now().plus(Duration.ofDays(7)); * String resourceUrl = "https://d111111abcdef8.cloudfront.net/s3ObjectKey"; * String keyPairId = "myKeyPairId"; * Path keyFile = myKeyFile; * * CannedSignerRequest cannedRequest = CannedSignerRequest.builder() * .resourceUrl(resourceUrl) * .privateKey(keyFile) * .keyPairId(keyPairId) * .expirationDate(expirationDate) * .build(); * SignedUrl signedUrl = utilities.getSignedUrlWithCannedPolicy(cannedRequest); * String url = signedUrl.url(); * } */ public SignedUrl getSignedUrlWithCannedPolicy(CannedSignerRequest request) { try { String resourceUrl = request.resourceUrl(); String cannedPolicy = SigningUtils.buildCannedPolicy(resourceUrl, request.expirationDate()); byte[] signatureBytes = SigningUtils.signWithSha1Rsa(cannedPolicy.getBytes(UTF_8), request.privateKey()); String urlSafeSignature = SigningUtils.makeBytesUrlSafe(signatureBytes); URI uri = URI.create(resourceUrl); String protocol = uri.getScheme(); String domain = uri.getHost(); String encodedPath = uri.getRawPath() + (uri.getQuery() != null ? "?" + uri.getRawQuery() + "&" : "?") + "Expires=" + request.expirationDate().getEpochSecond() + "&Signature=" + urlSafeSignature + "&Key-Pair-Id=" + request.keyPairId(); return DefaultSignedUrl.builder().protocol(protocol).domain(domain).encodedPath(encodedPath) .url(protocol + "://" + domain + encodedPath).build(); } catch (InvalidKeyException e) { throw SdkClientException.create("Could not sign url", e); } } /** * Returns a signed URL that provides tailored access to private content * based on an access time window and an ip range. The custom policy itself * is included as part of the signed URL (For a signed URL with canned * policy, there is no policy included in the signed URL). * For more information, see <a href= * "https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-creating-signed-url-custom-policy.html" * >Creating a signed URL using a custom policy</a>. * * <p> * This is a convenience which creates an instance of the {@link CustomSignerRequest.Builder} avoiding the need to * create one manually via {@link CustomSignerRequest#builder()} * * @param request * A {@link Consumer} that will call methods on {@link CustomSignerRequest.Builder} to create a request. * @return A signed URL that will permit access to distribution and S3 * objects as specified in the policy document. * * <p><b>Example Usage</b> * <p> * {@snippet : * //Generates signed URL String with custom policy, with an access window that begins in 2 days and ends in 7 days, * //for a specified IP range * CloudFrontUtilities utilities = CloudFrontUtilities.create(); * * Instant expirationDate = Instant.now().plus(Duration.ofDays(7)); * String resourceUrl = "https://d111111abcdef8.cloudfront.net/s3ObjectKey"; * String keyPairId = "myKeyPairId"; * PrivateKey privateKey = myPrivateKey; * Instant activeDate = Instant.now().plus(Duration.ofDays(2)); * String ipRange = "192.168.0.1/24"; * * SignedUrl signedUrl = utilities.getSignedUrlWithCustomPolicy(r -> r.resourceUrl(resourceUrl) * .privateKey(privateKey) * .keyPairId(keyPairId) * .expirationDate(expirationDate) * .activeDate(activeDate) * .ipRange(ipRange)); * String url = signedUrl.url(); * } */ public SignedUrl getSignedUrlWithCustomPolicy(Consumer<CustomSignerRequest.Builder> request) { return getSignedUrlWithCustomPolicy(CustomSignerRequest.builder().applyMutation(request).build()); } /** * Returns a signed URL that provides tailored access to private content * based on an access time window and an ip range. The custom policy itself * is included as part of the signed URL (For a signed URL with canned * policy, there is no policy included in the signed URL). * For more information, see <a href= * "https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-creating-signed-url-custom-policy.html" * >Creating a signed URL using a custom policy</a>. * * @param request * A {@link CustomSignerRequest} configured with the following values: * resourceUrl, privateKey, keyPairId, expirationDate, activeDate (optional), ipRange (optional) * @return A signed URL that will permit access to distribution and S3 * objects as specified in the policy document. * * <p><b>Example Usage</b> * <p> * {@snippet : * //Generates signed URL String with custom policy, with an access window that begins in 2 days and ends in 7 days, * //for a specified IP range * CloudFrontUtilities utilities = CloudFrontUtilities.create(); * * Instant expirationDate = Instant.now().plus(Duration.ofDays(7)); * String resourceUrl = "https://d111111abcdef8.cloudfront.net/s3ObjectKey"; * String keyPairId = "myKeyPairId"; * Path keyFile = myKeyFile; * Instant activeDate = Instant.now().plus(Duration.ofDays(2)); * String ipRange = "192.168.0.1/24"; * * CustomSignerRequest customRequest = CustomSignerRequest.builder() * .resourceUrl(resourceUrl) * .privateKey(keyFile) * .keyPairId(keyPairId) * .expirationDate(expirationDate) * .activeDate(activeDate) * .ipRange(ipRange) * .build(); * SignedUrl signedUrl = utilities.getSignedUrlWithCustomPolicy(customRequest); * String url = signedUrl.url(); * } */ public SignedUrl getSignedUrlWithCustomPolicy(CustomSignerRequest request) { try { String resourceUrl = request.resourceUrl(); String policy = SigningUtils.buildCustomPolicyForSignedUrl(request.resourceUrl(), request.activeDate(), request.expirationDate(), request.ipRange()); byte[] signatureBytes = SigningUtils.signWithSha1Rsa(policy.getBytes(UTF_8), request.privateKey()); String urlSafePolicy = SigningUtils.makeStringUrlSafe(policy); String urlSafeSignature = SigningUtils.makeBytesUrlSafe(signatureBytes); URI uri = URI.create(resourceUrl); String protocol = uri.getScheme(); String domain = uri.getHost(); String encodedPath = uri.getRawPath() + (uri.getQuery() != null ? "?" + uri.getRawQuery() + "&" : "?") + "Policy=" + urlSafePolicy + "&Signature=" + urlSafeSignature + "&Key-Pair-Id=" + request.keyPairId(); return DefaultSignedUrl.builder().protocol(protocol).domain(domain).encodedPath(encodedPath) .url(protocol + "://" + domain + encodedPath).build(); } catch (InvalidKeyException e) { throw SdkClientException.create("Could not sign url", e); } } /** * Generate signed cookies that allows access to a specific distribution and * resource path by applying access restrictions from a "canned" (simplified) * policy document. * For more information, see <a href= * "https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-setting-signed-cookie-canned-policy.html" * >Setting signed cookies using a canned policy</a>. * * <p> * This is a convenience which creates an instance of the {@link CannedSignerRequest.Builder} avoiding the need to * create one manually via {@link CannedSignerRequest#builder()} * * @param request * A {@link Consumer} that will call methods on {@link CannedSignerRequest.Builder} to create a request. * @return The signed cookies with canned policy. * * <p><b>Example Usage</b> * <p> * {@snippet : * //Generates signed Cookie for canned policy, valid for 7 days * CloudFrontUtilities utilities = CloudFrontUtilities.create(); * * Instant expirationDate = Instant.now().plus(Duration.ofDays(7)); * String resourceUrl = "https://d111111abcdef8.cloudfront.net/s3ObjectKey"; * String keyPairId = "myKeyPairId"; * PrivateKey privateKey = myPrivateKey; * * CookiesForCannedPolicy cookies = utilities.getSignedCookiesForCannedPolicy(r -> r.resourceUrl(resourceUrl) * .privateKey(privateKey) * .keyPairId(keyPairId) * .expirationDate(expirationDate)); * // Generates Set-Cookie header values to send to the viewer to allow access * String signatureHeaderValue = cookies.signatureHeaderValue(); * String keyPairIdHeaderValue = cookies.keyPairIdHeaderValue(); * String expiresHeaderValue = cookies.expiresHeaderValue(); * } */ public CookiesForCannedPolicy getCookiesForCannedPolicy(Consumer<CannedSignerRequest.Builder> request) { return getCookiesForCannedPolicy(CannedSignerRequest.builder().applyMutation(request).build()); } /** * Generate signed cookies that allows access to a specific distribution and * resource path by applying access restrictions from a "canned" (simplified) * policy document. * For more information, see <a href= * "https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-setting-signed-cookie-canned-policy.html" * >Setting signed cookies using a canned policy</a>. * * @param request * A {@link CannedSignerRequest} configured with the following values: * resourceUrl, privateKey, keyPairId, expirationDate * @return The signed cookies with canned policy. * * <p><b>Example Usage</b> * <p> * {@snippet : * //Generates signed Cookie for canned policy, valid for 7 days * CloudFrontUtilities utilities = CloudFrontUtilities.create(); * * Instant expirationDate = Instant.now().plus(Duration.ofDays(7)); * String resourceUrl = "https://d111111abcdef8.cloudfront.net/s3ObjectKey"; * String keyPairId = "myKeyPairId"; * Path keyFile = myKeyFile; * * CannedSignerRequest cannedRequest = CannedSignerRequest.builder() * .resourceUrl(resourceUrl) * .privateKey(keyFile) * .keyPairId(keyPairId) * .expirationDate(expirationDate) * .build(); * CookiesForCannedPolicy cookies = utilities.getCookiesForCannedPolicy(cannedRequest); * // Generates Set-Cookie header values to send to the viewer to allow access * String signatureHeaderValue = cookies.signatureHeaderValue(); * String keyPairIdHeaderValue = cookies.keyPairIdHeaderValue(); * String expiresHeaderValue = cookies.expiresHeaderValue(); * } */ public CookiesForCannedPolicy getCookiesForCannedPolicy(CannedSignerRequest request) { try { String cannedPolicy = SigningUtils.buildCannedPolicy(request.resourceUrl(), request.expirationDate()); byte[] signatureBytes = SigningUtils.signWithSha1Rsa(cannedPolicy.getBytes(UTF_8), request.privateKey()); String urlSafeSignature = SigningUtils.makeBytesUrlSafe(signatureBytes); String expiry = String.valueOf(request.expirationDate().getEpochSecond()); return DefaultCookiesForCannedPolicy.builder() .resourceUrl(request.resourceUrl()) .keyPairIdHeaderValue(KEY_PAIR_ID_KEY + "=" + request.keyPairId()) .signatureHeaderValue(SIGNATURE_KEY + "=" + urlSafeSignature) .expiresHeaderValue(EXPIRES_KEY + "=" + expiry).build(); } catch (InvalidKeyException e) { throw SdkClientException.create("Could not sign canned policy cookie", e); } } /** * Returns signed cookies that provides tailored access to private content based on an access time window and an ip range. * For more information, see <a href= * "https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-setting-signed-cookie-custom-policy.html" * >Setting signed cookies using a custom policy</a>. * * <p> * This is a convenience which creates an instance of the {@link CustomSignerRequest.Builder} avoiding the need to * create one manually via {@link CustomSignerRequest#builder()} * * @param request * A {@link Consumer} that will call methods on {@link CustomSignerRequest.Builder} to create a request. * @return The signed cookies with custom policy. * * <p><b>Example Usage</b> * <p> * {@snippet : * //Generates signed Cookie for custom policy, with an access window that begins in 2 days and ends in 7 days, * //for a specified IP range * CloudFrontUtilities utilities = CloudFrontUtilities.create(); * * Instant expirationDate = Instant.now().plus(Duration.ofDays(7)); * String resourceUrl = "https://d111111abcdef8.cloudfront.net/s3ObjectKey"; * String keyPairId = "myKeyPairId"; * PrivateKey privateKey = myPrivateKey; * Instant activeDate = Instant.now().plus(Duration.ofDays(2)); * String ipRange = "192.168.0.1/24"; * * CookiesForCustomPolicy cookies = utilities.getCookiesForCustomPolicy(r -> r.resourceUrl(resourceUrl) * .privateKey(privateKey) * .keyPairId(keyPairId) * .expirationDate(expirationDate) * .activeDate(activeDate) * .ipRange(ipRange)); * // Generates Set-Cookie header values to send to the viewer to allow access * String signatureHeaderValue = cookies.signatureHeaderValue(); * String keyPairIdHeaderValue = cookies.keyPairIdHeaderValue(); * String policyHeaderValue = cookies.policyHeaderValue(); * } */ public CookiesForCustomPolicy getCookiesForCustomPolicy(Consumer<CustomSignerRequest.Builder> request) { return getCookiesForCustomPolicy(CustomSignerRequest.builder().applyMutation(request).build()); } /** * Returns signed cookies that provides tailored access to private content based on an access time window and an ip range. * For more information, see <a href= * "https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-setting-signed-cookie-custom-policy.html" * >Setting signed cookies using a custom policy</a>. * * @param request * A {@link CustomSignerRequest} configured with the following values: * resourceUrl, privateKey, keyPairId, expirationDate, activeDate (optional), ipRange (optional) * @return The signed cookies with custom policy. * * <p><b>Example Usage</b> * <p> * {@snippet : * //Generates signed Cookie for custom policy, with an access window that begins in 2 days and ends in 7 days, * //for a specified IP range * CloudFrontUtilities utilities = CloudFrontUtilities.create(); * * Instant expirationDate = Instant.now().plus(Duration.ofDays(7)); * String resourceUrl = "https://d111111abcdef8.cloudfront.net/s3ObjectKey"; * String keyPairId = "myKeyPairId"; * Path keyFile = myKeyFile; * Instant activeDate = Instant.now().plus(Duration.ofDays(2)); * String ipRange = "192.168.0.1/24"; * * CustomSignerRequest customRequest = CustomSignerRequest.builder() * .resourceUrl(resourceUrl) * .privateKey(keyFile) * .keyPairId(keyFile) * .expirationDate(expirationDate) * .activeDate(activeDate) * .ipRange(ipRange) * .build(); * CookiesForCustomPolicy cookies = utilities.getCookiesForCustomPolicy(customRequest); * // Generates Set-Cookie header values to send to the viewer to allow access * String signatureHeaderValue = cookies.signatureHeaderValue(); * String keyPairIdHeaderValue = cookies.keyPairIdHeaderValue(); * String policyHeaderValue = cookies.policyHeaderValue(); * } */ public CookiesForCustomPolicy getCookiesForCustomPolicy(CustomSignerRequest request) { try { String policy = SigningUtils.buildCustomPolicy(request.resourceUrl(), request.activeDate(), request.expirationDate(), request.ipRange()); byte[] signatureBytes = SigningUtils.signWithSha1Rsa(policy.getBytes(UTF_8), request.privateKey()); String urlSafePolicy = SigningUtils.makeStringUrlSafe(policy); String urlSafeSignature = SigningUtils.makeBytesUrlSafe(signatureBytes); return DefaultCookiesForCustomPolicy.builder() .resourceUrl(request.resourceUrl()) .keyPairIdHeaderValue(KEY_PAIR_ID_KEY + "=" + request.keyPairId()) .signatureHeaderValue(SIGNATURE_KEY + "=" + urlSafeSignature) .policyHeaderValue(POLICY_KEY + "=" + urlSafePolicy).build(); } catch (InvalidKeyException e) { throw SdkClientException.create("Could not sign custom policy cookie", e); } } }
4,687
0
Create_ds/aws-sdk-java-v2/services/cloudfront/src/main/java/software/amazon/awssdk/services/cloudfront/internal
Create_ds/aws-sdk-java-v2/services/cloudfront/src/main/java/software/amazon/awssdk/services/cloudfront/internal/auth/Asn1Object.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.cloudfront.internal.auth; import java.io.IOException; import java.math.BigInteger; import software.amazon.awssdk.annotations.SdkInternalApi; @SdkInternalApi public class Asn1Object { protected final int type; protected final int length; protected final byte[] value; protected final int tag; /** * Construct a ASN.1 TLV. The TLV could be either a * constructed or primitive entity. * * <p>The first byte in DER encoding is made of following fields, * <pre> *------------------------------------------------- *|Bit 8|Bit 7|Bit 6|Bit 5|Bit 4|Bit 3|Bit 2|Bit 1| *------------------------------------------------- *| Class | CF | + Type | *------------------------------------------------- * </pre> * <ul> * <li>Class: Universal, Application, Context or Private * <li>CF: Constructed flag. If 1, the field is constructed. * <li>Type: This is actually called tag in ASN.1. It * indicates data type (Integer, String) or a construct * (sequence, choice, set). * </ul> * * @param tag Tag or Identifier * @param length Length of the field * @param value Encoded octet string for the field. */ public Asn1Object(int tag, int length, byte[] value) { this.tag = tag; this.type = tag & 0x1F; this.length = length; this.value = value.clone(); } public int getType() { return type; } public int getLength() { return length; } public byte[] getValue() { return value.clone(); } public boolean isConstructed() { return (tag & DerParser.CONSTRUCTED) == DerParser.CONSTRUCTED; } /** * For constructed field, return a parser for its content. * * @return A parser for the construct. */ public DerParser getParser() throws IOException { if (!isConstructed()) { throw new IOException("Invalid DER: can't parse primitive entity"); //$NON-NLS-1$ } return new DerParser(value); } /** * Get the value as integer */ public BigInteger getInteger() throws IOException { if (type != DerParser.INTEGER) { throw new IOException("Invalid DER: object is not integer"); //$NON-NLS-1$ } return new BigInteger(value); } /** * Get value as string. Most strings are treated * as Latin-1. */ public String getString() throws IOException { String encoding; switch (type) { // Not all are Latin-1 but it's the closest thing case DerParser.NUMERIC_STRING: case DerParser.PRINTABLE_STRING: case DerParser.VIDEOTEX_STRING: case DerParser.IA5_STRING: case DerParser.GRAPHIC_STRING: case DerParser.ISO646_STRING: case DerParser.GENERAL_STRING: encoding = "ISO-8859-1"; //$NON-NLS-1$ break; case DerParser.BMP_STRING: encoding = "UTF-16BE"; //$NON-NLS-1$ break; case DerParser.UTF8_STRING: encoding = "UTF-8"; //$NON-NLS-1$ break; case DerParser.UNIVERSAL_STRING: throw new IOException("Invalid DER: can't handle UCS-4 string"); //$NON-NLS-1$ default: throw new IOException("Invalid DER: object is not a string"); //$NON-NLS-1$ } return new String(value, encoding); } }
4,688
0
Create_ds/aws-sdk-java-v2/services/cloudfront/src/main/java/software/amazon/awssdk/services/cloudfront/internal
Create_ds/aws-sdk-java-v2/services/cloudfront/src/main/java/software/amazon/awssdk/services/cloudfront/internal/auth/PemObject.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.cloudfront.internal.auth; import software.amazon.awssdk.annotations.SdkInternalApi; @SdkInternalApi public class PemObject { private final String beginMarker; private final byte[] derBytes; public PemObject(String beginMarker, byte[] derBytes) { this.beginMarker = beginMarker; this.derBytes = derBytes.clone(); } public String getBeginMarker() { return beginMarker; } public byte[] getDerBytes() { return derBytes.clone(); } public PemObjectType getPemObjectType() { return PemObjectType.fromBeginMarker(beginMarker); } }
4,689
0
Create_ds/aws-sdk-java-v2/services/cloudfront/src/main/java/software/amazon/awssdk/services/cloudfront/internal
Create_ds/aws-sdk-java-v2/services/cloudfront/src/main/java/software/amazon/awssdk/services/cloudfront/internal/auth/Pem.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.cloudfront.internal.auth; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.security.PrivateKey; import java.security.PublicKey; import java.security.spec.InvalidKeySpecException; import java.util.ArrayList; import java.util.Base64; import java.util.List; import java.util.regex.Pattern; import software.amazon.awssdk.annotations.SdkInternalApi; @SdkInternalApi public final class Pem { private static final String BEGIN_MARKER = "-----BEGIN "; private static final Pattern BEGIN = Pattern.compile("BEGIN", Pattern.LITERAL); private Pem() { } /** * Returns the first private key that is found from the input stream of a * PEM file. * * @throws InvalidKeySpecException * if failed to convert the DER bytes into a private key. * @throws IllegalArgumentException * if no private key is found. */ public static PrivateKey readPrivateKey(InputStream is) throws InvalidKeySpecException, IOException { List<PemObject> objects = readPemObjects(is); for (PemObject object : objects) { switch (object.getPemObjectType()) { case PRIVATE_KEY_PKCS1: return Rsa.privateKeyFromPkcs1(object.getDerBytes()); case PRIVATE_KEY_PKCS8: return Rsa.privateKeyFromPkcs8(object.getDerBytes()); default: break; } } throw new IllegalArgumentException("Found no private key"); } /** * Returns the first public key that is found from the input stream of a PEM * file. * * @throws InvalidKeySpecException * if failed to convert the DER bytes into a public key. * @throws IllegalArgumentException * if no public key is found. */ public static PublicKey readPublicKey(InputStream is) throws InvalidKeySpecException, IOException { List<PemObject> objects = readPemObjects(is); for (PemObject object : objects) { if (object.getPemObjectType() == PemObjectType.PUBLIC_KEY_X509) { return Rsa.publicKeyFrom(object.getDerBytes()); } } throw new IllegalArgumentException("Found no public key"); } /** * A lower level API used to returns all PEM objects that can be read off * from the input stream of a PEM file. * <p> * This method can be useful if more than one PEM object of different types * are embedded in the same PEM file. */ public static List<PemObject> readPemObjects(InputStream is) throws IOException { List<PemObject> pemContents = new ArrayList<>(); /* * State of reading: set to true if reading content between a * begin-marker and end-marker; false otherwise. */ boolean readingContent = false; String beginMarker = null; String endMarker = null; StringBuilder sb = null; String line; try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) { while ((line = reader.readLine()) != null) { if (readingContent) { if (line.contains(endMarker)) { pemContents.add(new PemObject(beginMarker, Base64.getDecoder().decode(sb.toString()))); readingContent = false; } else { sb.append(line.trim()); } } else { if (line.contains(BEGIN_MARKER)) { readingContent = true; beginMarker = line.trim(); endMarker = BEGIN.matcher(beginMarker).replaceAll("END"); sb = new StringBuilder(); } } } return pemContents; } } }
4,690
0
Create_ds/aws-sdk-java-v2/services/cloudfront/src/main/java/software/amazon/awssdk/services/cloudfront/internal
Create_ds/aws-sdk-java-v2/services/cloudfront/src/main/java/software/amazon/awssdk/services/cloudfront/internal/auth/DerParser.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.cloudfront.internal.auth; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; import software.amazon.awssdk.annotations.SdkInternalApi; @SdkInternalApi public class DerParser { // Classes public static final int UNIVERSAL = 0x00; public static final int APPLICATION = 0x40; public static final int CONTEXT = 0x80; public static final int PRIVATE = 0xC0; // Constructed Flag public static final int CONSTRUCTED = 0x20; // Tag and data types public static final int ANY = 0x00; public static final int BOOLEAN = 0x01; public static final int INTEGER = 0x02; public static final int BIT_STRING = 0x03; public static final int OCTET_STRING = 0x04; public static final int NULL = 0x05; public static final int OBJECT_IDENTIFIER = 0x06; public static final int REAL = 0x09; public static final int ENUMERATED = 0x0a; public static final int RELATIVE_OID = 0x0d; public static final int SEQUENCE = 0x10; public static final int SET = 0x11; public static final int NUMERIC_STRING = 0x12; public static final int PRINTABLE_STRING = 0x13; public static final int T61_STRING = 0x14; public static final int VIDEOTEX_STRING = 0x15; public static final int IA5_STRING = 0x16; public static final int GRAPHIC_STRING = 0x19; public static final int ISO646_STRING = 0x1A; public static final int GENERAL_STRING = 0x1B; public static final int UTF8_STRING = 0x0C; public static final int UNIVERSAL_STRING = 0x1C; public static final int BMP_STRING = 0x1E; public static final int UTC_TIME = 0x17; public static final int GENERALIZED_TIME = 0x18; protected final InputStream in; /** * Create a new DER decoder from an input stream. * * @param in * The DER encoded stream */ public DerParser(InputStream in) { this.in = in; } /** * Create a new DER decoder from a byte array. * * @param bytes * the encoded bytes */ public DerParser(byte[] bytes) { this(new ByteArrayInputStream(bytes)); } /** * Read next object. If it's constructed, the value holds encoded content * and it should be parsed by a new parser from * {@code Asn1Object.getParser}. */ public Asn1Object read() throws IOException { int tag = in.read(); if (tag == -1) { throw new IOException("Invalid DER: stream too short, missing tag"); //$NON-NLS-1$ } int length = getLength(); byte[] value = new byte[length]; int n = in.read(value); if (n < length) { throw new IOException( "Invalid DER: stream too short, missing value"); //$NON-NLS-1$ } return new Asn1Object(tag, length, value); } /** * Decode the length of the field. Can only support length encoding up to 4 * octets. * * In BER/DER encoding, length can be encoded in 2 forms, * <ul> * <li>Short form. One octet. Bit 8 has value "0" and bits 7-1 give the * length. * <li>Long form. Two to 127 octets (only 4 is supported here). Bit 8 of * first octet has value "1" and bits 7-1 give the number of additional * length octets. Second and following octets give the length, base 256, * most significant digit first. * </ul> * * @return The length as integer */ private int getLength() throws IOException { int i = in.read(); if (i == -1) { throw new IOException("Invalid DER: length missing"); //$NON-NLS-1$ } // A single byte short length if ((i & ~0x7F) == 0) { return i; } int num = i & 0x7F; // We can't handle length longer than 4 bytes if (i >= 0xFF || num > 4) { throw new IOException("Invalid DER: length field too big (" //$NON-NLS-1$ + i + ")"); //$NON-NLS-1$ } byte[] bytes = new byte[num]; int n = in.read(bytes); if (n < num) { throw new IOException("Invalid DER: length too short"); //$NON-NLS-1$ } return new BigInteger(1, bytes).intValue(); } }
4,691
0
Create_ds/aws-sdk-java-v2/services/cloudfront/src/main/java/software/amazon/awssdk/services/cloudfront/internal
Create_ds/aws-sdk-java-v2/services/cloudfront/src/main/java/software/amazon/awssdk/services/cloudfront/internal/auth/PemObjectType.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.cloudfront.internal.auth; import java.util.Arrays; import software.amazon.awssdk.annotations.SdkInternalApi; @SdkInternalApi public enum PemObjectType { PRIVATE_KEY_PKCS1("-----BEGIN RSA PRIVATE KEY-----"), PRIVATE_KEY_PKCS8("-----BEGIN PRIVATE KEY-----"), PUBLIC_KEY_X509("-----BEGIN PUBLIC KEY-----"), CERTIFICATE_X509("-----BEGIN CERTIFICATE-----") ; private final String beginMarker; PemObjectType(String beginMarker) { this.beginMarker = beginMarker; } public String getBeginMarker() { return beginMarker; } public static PemObjectType fromBeginMarker(String beginMarker) { return Arrays.stream(values()).filter(e -> e.getBeginMarker().equals(beginMarker)).findFirst().orElse(null); } }
4,692
0
Create_ds/aws-sdk-java-v2/services/cloudfront/src/main/java/software/amazon/awssdk/services/cloudfront/internal
Create_ds/aws-sdk-java-v2/services/cloudfront/src/main/java/software/amazon/awssdk/services/cloudfront/internal/auth/Rsa.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.cloudfront.internal.auth; import java.io.IOException; import java.math.BigInteger; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.spec.EncodedKeySpec; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.RSAPrivateCrtKeySpec; import java.security.spec.X509EncodedKeySpec; import software.amazon.awssdk.annotations.SdkInternalApi; @SdkInternalApi public final class Rsa { private static final String RSA = "RSA"; private Rsa() { } /** * Returns a private key constructed from the given DER bytes in PKCS#8 format. */ public static PrivateKey privateKeyFromPkcs8(byte[] pkcs8) throws InvalidKeySpecException { try { EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(pkcs8); KeyFactory keyFactory = KeyFactory.getInstance(RSA); return keyFactory.generatePrivate(privateKeySpec); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); } } /** * Returns a private key constructed from the given DER bytes in PKCS#1 format. */ public static PrivateKey privateKeyFromPkcs1(byte[] pkcs1) throws InvalidKeySpecException { try { RSAPrivateCrtKeySpec privateKeySpec = newRsaPrivateCrtKeySpec(pkcs1); KeyFactory keyFactory = KeyFactory.getInstance(RSA); return keyFactory.generatePrivate(privateKeySpec); } catch (IOException e) { throw new IllegalArgumentException(e); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); } } /** * Returns a public key constructed from the given DER bytes. */ public static PublicKey publicKeyFrom(byte[] derBytes) throws InvalidKeySpecException { try { KeyFactory keyFactory = KeyFactory.getInstance(RSA); EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(derBytes); return keyFactory.generatePublic(publicKeySpec); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); } } // Extracted from: // http://oauth.googlecode.com/svn/code/branches/jmeter/jmeter/src/main/java/org/apache/jmeter/protocol/oauth/sampler/PrivateKeyReader.java // See p.41 of http://www.emc.com/emc-plus/rsa-labs/pkcs/files/h11300-wp-pkcs-1v2-2-rsa-cryptography-standard.pdf /**************************************************************************** * Amazon Modifications: Copyright 2014 Amazon.com, Inc. or its affiliates. * All Rights Reserved. ***************************************************************************** * Copyright (c) 1998-2010 AOL Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **************************************************************************** * Convert PKCS#1 encoded private key into RSAPrivateCrtKeySpec. * * <p>The ASN.1 syntax for the private key with CRT is * * <pre> * -- * -- Representation of RSA private key with information for the CRT algorithm. * -- * RSAPrivateKey ::= SEQUENCE { * version Version, * modulus INTEGER, -- n * publicExponent INTEGER, -- e * privateExponent INTEGER, -- d * prime1 INTEGER, -- p * prime2 INTEGER, -- q * exponent1 INTEGER, -- d mod (p-1) * exponent2 INTEGER, -- d mod (q-1) * coefficient INTEGER, -- (inverse of q) mod p * otherPrimeInfos OtherPrimeInfos OPTIONAL * } * </pre> * * @param keyInPkcs1 * PKCS#1 encoded key * @throws IOException */ private static RSAPrivateCrtKeySpec newRsaPrivateCrtKeySpec(byte[] keyInPkcs1) throws IOException { DerParser parser = new DerParser(keyInPkcs1); Asn1Object sequence = parser.read(); if (sequence.getType() != DerParser.SEQUENCE) { throw new IllegalArgumentException("Invalid DER: not a sequence"); //$NON-NLS-1$ } // Parse inside the sequence parser = sequence.getParser(); parser.read(); // Skip version BigInteger modulus = parser.read().getInteger(); BigInteger publicExp = parser.read().getInteger(); BigInteger privateExp = parser.read().getInteger(); BigInteger prime1 = parser.read().getInteger(); BigInteger prime2 = parser.read().getInteger(); BigInteger exp1 = parser.read().getInteger(); BigInteger exp2 = parser.read().getInteger(); BigInteger crtCoef = parser.read().getInteger(); return new RSAPrivateCrtKeySpec(modulus, publicExp, privateExp, prime1, prime2, exp1, exp2, crtCoef); } }
4,693
0
Create_ds/aws-sdk-java-v2/services/cloudfront/src/main/java/software/amazon/awssdk/services/cloudfront/internal
Create_ds/aws-sdk-java-v2/services/cloudfront/src/main/java/software/amazon/awssdk/services/cloudfront/internal/utils/SigningUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.cloudfront.internal.utils; import static java.nio.charset.StandardCharsets.UTF_8; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.SecureRandom; import java.security.Signature; import java.security.SignatureException; import java.time.Instant; import java.util.Base64; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.services.cloudfront.internal.auth.Pem; import software.amazon.awssdk.services.cloudfront.internal.auth.Rsa; import software.amazon.awssdk.utils.IoUtils; import software.amazon.awssdk.utils.StringUtils; @SdkInternalApi public final class SigningUtils { private SigningUtils() { } /** * Returns a "canned" policy for the given parameters. * For more information, see * <a href = * "https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-creating-signed-url-canned-policy.html" * >Creating a signed URL using a canned policy</a> * or * <a href= * "https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-setting-signed-cookie-canned-policy.html" * >Setting signed cookies using a canned policy</a>. */ public static String buildCannedPolicy(String resourceUrl, Instant expirationDate) { return "{\"Statement\":[{\"Resource\":\"" + resourceUrl + "\",\"Condition\":{\"DateLessThan\":{\"AWS:EpochTime\":" + expirationDate.getEpochSecond() + "}}}]}"; } /** * Returns a custom policy for the given parameters. * For more information, see <a href= * "https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-creating-signed-url-custom-policy.html" * >Creating a signed URL using a custom policy</a> * or * <a href= * "https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-setting-signed-cookie-custom-policy.html" * >Setting signed cookies using a custom policy</a>. */ public static String buildCustomPolicy(String resourceUrl, Instant activeDate, Instant expirationDate, String ipAddress) { return "{\"Statement\": [{" + "\"Resource\":\"" + resourceUrl + "\"" + ",\"Condition\":{" + "\"DateLessThan\":{\"AWS:EpochTime\":" + expirationDate.getEpochSecond() + "}" + (ipAddress == null ? "" : ",\"IpAddress\":{\"AWS:SourceIp\":\"" + ipAddress + "\"}" ) + (activeDate == null ? "" : ",\"DateGreaterThan\":{\"AWS:EpochTime\":" + activeDate.getEpochSecond() + "}" ) + "}}]}"; } /** * Converts the given data to be safe for use in signed URLs for a private * distribution by using specialized Base64 encoding. */ public static String makeBytesUrlSafe(byte[] bytes) { byte[] encoded = Base64.getEncoder().encode(bytes); for (int i = 0; i < encoded.length; i++) { switch (encoded[i]) { case '+': encoded[i] = '-'; continue; case '=': encoded[i] = '_'; continue; case '/': encoded[i] = '~'; continue; default: } } return new String(encoded, UTF_8); } /** * Converts the given string to be safe for use in signed URLs for a private * distribution. */ public static String makeStringUrlSafe(String str) { return makeBytesUrlSafe(str.getBytes(UTF_8)); } /** * Signs the data given with the private key given, using the SHA1withRSA * algorithm provided by bouncy castle. */ public static byte[] signWithSha1Rsa(byte[] dataToSign, PrivateKey privateKey) throws InvalidKeyException { try { Signature signature = Signature.getInstance("SHA1withRSA"); SecureRandom random = new SecureRandom(); signature.initSign(privateKey, random); signature.update(dataToSign); return signature.sign(); } catch (NoSuchAlgorithmException | SignatureException e) { throw new IllegalStateException(e); } } /** * Generate a policy document that describes custom access permissions to * apply via a private distribution's signed URL. * * @param resourceUrl * The HTTP/S resource path that restricts which distribution and * S3 objects will be accessible in a signed URL, i.e., * <tt>"https://" + distributionName + "/" + objectKey</tt> (may * also include URL parameters). The '*' and '?' characters can * be used as a wildcards to allow multi-character or single-character * matches respectively: * <ul> * <li><tt>*</tt> : All distributions/objects will be accessible</li> * <li><tt>a1b2c3d4e5f6g7.cloudfront.net/*</tt> : All objects * within the distribution a1b2c3d4e5f6g7 will be accessible</li> * <li><tt>a1b2c3d4e5f6g7.cloudfront.net/path/to/object.txt</tt> * : Only the S3 object named <tt>path/to/object.txt</tt> in the * distribution a1b2c3d4e5f6g7 will be accessible.</li> * </ul> * @param activeDate * An optional UTC time and date when the signed URL will become * active. If null, the signed URL will be active as soon as it * is created. * @param expirationDate * The UTC time and date when the signed URL will expire. REQUIRED. * @param limitToIpAddressCidr * An optional range of client IP addresses that will be allowed * to access the distribution, specified as an IPv4 CIDR range * (IPv6 format is not supported). If null, the CIDR will be omitted * and any client will be permitted. * @return A policy document describing the access permission to apply when * generating a signed URL. */ public static String buildCustomPolicyForSignedUrl(String resourceUrl, Instant activeDate, Instant expirationDate, String limitToIpAddressCidr) { if (expirationDate == null) { throw SdkClientException.create("Expiration date must be provided to sign CloudFront URLs"); } if (resourceUrl == null) { resourceUrl = "*"; } return buildCustomPolicy(resourceUrl, activeDate, expirationDate, limitToIpAddressCidr); } /** * Creates a private key from the file given, either in pem or der format. * Other formats will cause an exception to be thrown. */ public static PrivateKey loadPrivateKey(Path keyFile) throws Exception { if (StringUtils.lowerCase(keyFile.toString()).endsWith(".pem")) { try (InputStream is = Files.newInputStream(keyFile)) { return Pem.readPrivateKey(is); } } if (StringUtils.lowerCase(keyFile.toString()).endsWith(".der")) { try (InputStream is = Files.newInputStream(keyFile)) { return Rsa.privateKeyFromPkcs8(IoUtils.toByteArray(is)); } } throw SdkClientException.create("Unsupported file type for private key"); } }
4,694
0
Create_ds/aws-sdk-java-v2/services/cloudfront/src/main/java/software/amazon/awssdk/services/cloudfront/internal
Create_ds/aws-sdk-java-v2/services/cloudfront/src/main/java/software/amazon/awssdk/services/cloudfront/internal/url/DefaultSignedUrl.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.cloudfront.internal.url; import java.util.Objects; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.services.cloudfront.url.SignedUrl; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; @Immutable @ThreadSafe @SdkInternalApi public final class DefaultSignedUrl implements SignedUrl, ToCopyableBuilder<DefaultSignedUrl.Builder, DefaultSignedUrl> { private final String protocol; private final String domain; private final String encodedPath; private final String url; private DefaultSignedUrl(Builder builder) { this.protocol = builder.protocol; this.domain = builder.domain; this.encodedPath = builder.encodedPath; this.url = builder.url; } public static Builder builder() { return new Builder(); } @Override public Builder toBuilder() { return new Builder(this); } @Override public String toString() { return ToString.builder("DefaultSignedUrl") .add("url", url) .build(); } @Override public String protocol() { return protocol; } @Override public String domain() { return domain; } @Override public String encodedPath() { return encodedPath; } @Override public String url() { return url; } @Override public SdkHttpRequest createHttpGetRequest() { return SdkHttpRequest.builder() .encodedPath(encodedPath) .host(domain) .method(SdkHttpMethod.GET) .protocol(protocol) .build(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DefaultSignedUrl signedUrl = (DefaultSignedUrl) o; return Objects.equals(protocol, signedUrl.protocol) && Objects.equals(domain, signedUrl.domain) && Objects.equals(encodedPath, signedUrl.encodedPath) && Objects.equals(url, signedUrl.url); } @Override public int hashCode() { int result = protocol != null ? protocol.hashCode() : 0; result = 31 * result + (domain != null ? domain.hashCode() : 0); result = 31 * result + (encodedPath != null ? encodedPath.hashCode() : 0); result = 31 * result + (url != null ? url.hashCode() : 0); return result; } public static final class Builder implements CopyableBuilder<Builder, DefaultSignedUrl> { private String protocol; private String domain; private String encodedPath; private String url; private Builder() { } private Builder(DefaultSignedUrl signedUrl) { this.protocol = signedUrl.protocol; this.domain = signedUrl.domain; this.encodedPath = signedUrl.encodedPath; this.url = signedUrl.url; } /** * Configure the protocol */ public Builder protocol(String protocol) { this.protocol = protocol; return this; } /** * Configure the domain */ public Builder domain(String domain) { this.domain = domain; return this; } /** * Configure the encoded path */ public Builder encodedPath(String encodedPath) { this.encodedPath = encodedPath; return this; } /** * Configure the signed URL */ public Builder url(String url) { this.url = url; return this; } @Override public DefaultSignedUrl build() { return new DefaultSignedUrl(this); } } }
4,695
0
Create_ds/aws-sdk-java-v2/services/cloudfront/src/main/java/software/amazon/awssdk/services/cloudfront/internal
Create_ds/aws-sdk-java-v2/services/cloudfront/src/main/java/software/amazon/awssdk/services/cloudfront/internal/cookie/DefaultCookiesForCustomPolicy.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.cloudfront.internal.cookie; import java.net.URI; import java.util.Objects; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.services.cloudfront.cookie.CookiesForCustomPolicy; import software.amazon.awssdk.utils.ToString; @Immutable @ThreadSafe @SdkInternalApi public final class DefaultCookiesForCustomPolicy implements CookiesForCustomPolicy { private final String resourceUrl; private final String signatureHeaderValue; private final String keyPairIdHeaderValue; private final String policyHeaderValue; private DefaultCookiesForCustomPolicy(DefaultBuilder builder) { this.resourceUrl = builder.resourceUrl; this.signatureHeaderValue = builder.signatureHeaderValue; this.keyPairIdHeaderValue = builder.keyPairIdHeaderValue; this.policyHeaderValue = builder.policyHeaderValue; } public static Builder builder() { return new DefaultBuilder(); } @Override public Builder toBuilder() { return new DefaultBuilder(this); } @Override public String toString() { return ToString.builder("DefaultCookiesForCustomPolicy") .add("resourceUrl", resourceUrl) .add("signatureHeaderValue", signatureHeaderValue) .add("keyPairIdHeaderValue", keyPairIdHeaderValue) .add("policyHeaderValue", policyHeaderValue) .build(); } @Override public String resourceUrl() { return resourceUrl; } @Override public SdkHttpRequest createHttpGetRequest() { return SdkHttpRequest.builder() .uri(URI.create(resourceUrl)) .appendHeader(COOKIE, policyHeaderValue()) .appendHeader(COOKIE, signatureHeaderValue()) .appendHeader(COOKIE, keyPairIdHeaderValue()) .method(SdkHttpMethod.GET) .build(); } @Override public String signatureHeaderValue() { return signatureHeaderValue; } @Override public String keyPairIdHeaderValue() { return keyPairIdHeaderValue; } @Override public String policyHeaderValue() { return policyHeaderValue; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DefaultCookiesForCustomPolicy cookie = (DefaultCookiesForCustomPolicy) o; return Objects.equals(keyPairIdHeaderValue, cookie.keyPairIdHeaderValue) && Objects.equals(signatureHeaderValue, cookie.signatureHeaderValue) && Objects.equals(resourceUrl, cookie.resourceUrl) && Objects.equals(policyHeaderValue, cookie.policyHeaderValue); } @Override public int hashCode() { int result = keyPairIdHeaderValue != null ? keyPairIdHeaderValue.hashCode() : 0; result = 31 * result + (signatureHeaderValue != null ? signatureHeaderValue.hashCode() : 0); result = 31 * result + (resourceUrl != null ? resourceUrl.hashCode() : 0); result = 31 * result + (policyHeaderValue != null ? policyHeaderValue.hashCode() : 0); return result; } private static final class DefaultBuilder implements CookiesForCustomPolicy.Builder { private String resourceUrl; private String signatureHeaderValue; private String keyPairIdHeaderValue; private String policyHeaderValue; private DefaultBuilder() { } private DefaultBuilder(DefaultCookiesForCustomPolicy cookies) { this.resourceUrl = cookies.resourceUrl; this.signatureHeaderValue = cookies.signatureHeaderValue; this.keyPairIdHeaderValue = cookies.keyPairIdHeaderValue; this.policyHeaderValue = cookies.policyHeaderValue; } @Override public Builder resourceUrl(String resourceUrl) { this.resourceUrl = resourceUrl; return this; } @Override public Builder signatureHeaderValue(String signatureHeaderValue) { this.signatureHeaderValue = signatureHeaderValue; return this; } @Override public Builder keyPairIdHeaderValue(String keyPairIdHeaderValue) { this.keyPairIdHeaderValue = keyPairIdHeaderValue; return this; } @Override public Builder policyHeaderValue(String policyHeaderValue) { this.policyHeaderValue = policyHeaderValue; return this; } @Override public DefaultCookiesForCustomPolicy build() { return new DefaultCookiesForCustomPolicy(this); } } }
4,696
0
Create_ds/aws-sdk-java-v2/services/cloudfront/src/main/java/software/amazon/awssdk/services/cloudfront/internal
Create_ds/aws-sdk-java-v2/services/cloudfront/src/main/java/software/amazon/awssdk/services/cloudfront/internal/cookie/DefaultCookiesForCannedPolicy.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.cloudfront.internal.cookie; import java.net.URI; import java.util.Objects; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.services.cloudfront.cookie.CookiesForCannedPolicy; import software.amazon.awssdk.utils.ToString; @Immutable @ThreadSafe @SdkInternalApi public final class DefaultCookiesForCannedPolicy implements CookiesForCannedPolicy { private final String resourceUrl; private final String keyPairIdHeaderValue; private final String signatureHeaderValue; private final String expiresHeaderValue; private DefaultCookiesForCannedPolicy(DefaultBuilder builder) { this.resourceUrl = builder.resourceUrl; this.keyPairIdHeaderValue = builder.keyPairIdHeaderValue; this.signatureHeaderValue = builder.signatureHeaderValue; this.expiresHeaderValue = builder.expiresHeaderValue; } public static Builder builder() { return new DefaultBuilder(); } @Override public Builder toBuilder() { return new DefaultBuilder(this); } @Override public String toString() { return ToString.builder("DefaultCookiesForCannedPolicy") .add("resourceUrl", resourceUrl) .add("signatureHeaderValue", signatureHeaderValue) .add("keyPairIdHeaderValue", keyPairIdHeaderValue) .add("expiresHeaderValue", expiresHeaderValue) .build(); } @Override public String resourceUrl() { return resourceUrl; } @Override public SdkHttpRequest createHttpGetRequest() { return SdkHttpRequest.builder() .uri(URI.create(resourceUrl)) .appendHeader(COOKIE, signatureHeaderValue()) .appendHeader(COOKIE, keyPairIdHeaderValue()) .appendHeader(COOKIE, expiresHeaderValue()) .method(SdkHttpMethod.GET) .build(); } @Override public String signatureHeaderValue() { return signatureHeaderValue; } @Override public String keyPairIdHeaderValue() { return keyPairIdHeaderValue; } @Override public String expiresHeaderValue() { return expiresHeaderValue; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DefaultCookiesForCannedPolicy cookie = (DefaultCookiesForCannedPolicy) o; return Objects.equals(keyPairIdHeaderValue, cookie.keyPairIdHeaderValue) && Objects.equals(signatureHeaderValue, cookie.signatureHeaderValue) && Objects.equals(resourceUrl, cookie.resourceUrl) && Objects.equals(expiresHeaderValue, cookie.expiresHeaderValue); } @Override public int hashCode() { int result = keyPairIdHeaderValue != null ? keyPairIdHeaderValue.hashCode() : 0; result = 31 * result + (signatureHeaderValue != null ? signatureHeaderValue.hashCode() : 0); result = 31 * result + (resourceUrl != null ? resourceUrl.hashCode() : 0); result = 31 * result + (expiresHeaderValue != null ? expiresHeaderValue.hashCode() : 0); return result; } private static final class DefaultBuilder implements CookiesForCannedPolicy.Builder { private String resourceUrl; private String signatureHeaderValue; private String keyPairIdHeaderValue; private String expiresHeaderValue; private DefaultBuilder() { } private DefaultBuilder(DefaultCookiesForCannedPolicy cookies) { this.resourceUrl = cookies.resourceUrl; this.signatureHeaderValue = cookies.signatureHeaderValue; this.keyPairIdHeaderValue = cookies.keyPairIdHeaderValue; this.expiresHeaderValue = cookies.expiresHeaderValue; } @Override public Builder resourceUrl(String resourceUrl) { this.resourceUrl = resourceUrl; return this; } @Override public Builder signatureHeaderValue(String signatureHeaderValue) { this.signatureHeaderValue = signatureHeaderValue; return this; } @Override public Builder keyPairIdHeaderValue(String keyPairIdHeaderValue) { this.keyPairIdHeaderValue = keyPairIdHeaderValue; return this; } @Override public Builder expiresHeaderValue(String expiresHeaderValue) { this.expiresHeaderValue = expiresHeaderValue; return this; } @Override public DefaultCookiesForCannedPolicy build() { return new DefaultCookiesForCannedPolicy(this); } } }
4,697
0
Create_ds/aws-sdk-java-v2/services/cloudfront/src/main/java/software/amazon/awssdk/services/cloudfront
Create_ds/aws-sdk-java-v2/services/cloudfront/src/main/java/software/amazon/awssdk/services/cloudfront/url/SignedUrl.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.cloudfront.url; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.http.SdkHttpRequest; /** * Base interface class for CloudFront signed URLs */ @SdkPublicApi public interface SignedUrl { /** * Returns the protocol, i.e., HTTPS / HTTP */ String protocol(); /** * Returns the CloudFront domain, e.g., d1npcfkc2mojrf.cloudfront.net */ String domain(); /** * Returns the encoded path of the signed URL */ String encodedPath(); /** * Returns the signed URL that can be provided to users to access your private content */ String url(); /** * Generates an HTTP GET request that can be executed by an HTTP client to access the resource */ SdkHttpRequest createHttpGetRequest(); }
4,698
0
Create_ds/aws-sdk-java-v2/services/cloudfront/src/main/java/software/amazon/awssdk/services/cloudfront
Create_ds/aws-sdk-java-v2/services/cloudfront/src/main/java/software/amazon/awssdk/services/cloudfront/model/CloudFrontSignerRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.cloudfront.model; import java.security.PrivateKey; import java.time.Instant; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; /** * Base interface class for requests to generate a CloudFront signed URL or signed cookie */ @Immutable @ThreadSafe @SdkPublicApi public interface CloudFrontSignerRequest { /** * Returns the resource URL, i.e., the unsigned URL */ String resourceUrl(); /** * Returns the private key used to generate the signature */ PrivateKey privateKey(); /** * Returns the key pair ID, i.e., the public key ID for the CloudFront public key whose corresponding private key you're * using to generate the signature */ String keyPairId(); /** * Returns the expiration date, after which users will no longer be able to use the signed URL/cookie to access your * private content */ Instant expirationDate(); }
4,699