index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/aws-sdk-java-v2/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,900
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,901
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,902
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,903
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,904
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,905
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,906
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,907
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,908
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,909
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,910
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,911
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,912
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,913
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,914
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,915
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,916
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,917
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,918
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,919
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,920
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,921
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,922
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,923
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,924
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,925
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,926
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,927
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,928
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,929
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,930
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,931
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,932
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,933
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,934
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,935
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,936
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,937
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,938
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,939
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,940
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,941
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,942
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,943
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,944
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,945
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,946
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,947
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,948
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,949
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,950
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,951
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,952
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,953
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,954
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,955
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,956
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,957
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,958
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,959
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,960
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,961
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,962
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,963
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,964
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,965
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,966
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,967
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,968
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,969
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,970
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,971
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,972
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/CannedSignerRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.nio.file.Path; import java.security.PrivateKey; import java.time.Instant; import java.util.Objects; 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.services.cloudfront.internal.utils.SigningUtils; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * Request to generate CloudFront signed URLs or signed cookies with a canned policy */ @Immutable @ThreadSafe @SdkPublicApi public final class CannedSignerRequest implements CloudFrontSignerRequest, ToCopyableBuilder<CannedSignerRequest.Builder, CannedSignerRequest> { private final String resourceUrl; private final PrivateKey privateKey; private final String keyPairId; private final Instant expirationDate; private CannedSignerRequest(DefaultBuilder builder) { this.resourceUrl = builder.resourceUrl; this.privateKey = builder.privateKey; this.keyPairId = builder.keyPairId; this.expirationDate = builder.expirationDate; } /** * Create a builder that can be used to create a {@link CannedSignerRequest} */ public static Builder builder() { return new DefaultBuilder(); } @Override public Builder toBuilder() { return new DefaultBuilder(this); } @Override public String resourceUrl() { return resourceUrl; } @Override public PrivateKey privateKey() { return privateKey; } @Override public String keyPairId() { return keyPairId; } @Override public Instant expirationDate() { return expirationDate; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CannedSignerRequest cookie = (CannedSignerRequest) o; return Objects.equals(resourceUrl, cookie.resourceUrl) && Objects.equals(privateKey, cookie.privateKey) && Objects.equals(keyPairId, cookie.keyPairId) && Objects.equals(expirationDate, cookie.expirationDate); } @Override public int hashCode() { int result = resourceUrl != null ? resourceUrl.hashCode() : 0; result = 31 * result + (privateKey != null ? privateKey.hashCode() : 0); result = 31 * result + (keyPairId != null ? keyPairId.hashCode() : 0); result = 31 * result + (expirationDate != null ? expirationDate.hashCode() : 0); return result; } @NotThreadSafe @SdkPublicApi public interface Builder extends CopyableBuilder<CannedSignerRequest.Builder, CannedSignerRequest> { /** * Configure the resource URL to be signed * <p> * The URL or path that uniquely identifies a resource within a * distribution. For standard distributions the resource URL will * be <tt>"http://" + distributionName + "/" + objectKey</tt> * (may also include URL parameters. For distributions with the * HTTPS required protocol, the resource URL must start with * <tt>"https://"</tt> */ Builder resourceUrl(String resourceUrl); /** * Configure the private key to be used to sign the policy. * Takes a PrivateKey object directly */ Builder privateKey(PrivateKey privateKey); /** * Configure the private key to be used to sign the policy. * Takes a Path to the key file, and loads it to return a PrivateKey object */ Builder privateKey(Path keyFile) throws Exception; /** * Configure the ID of the key pair stored in the AWS account */ Builder keyPairId(String keyPairId); /** * Configure the expiration date of the signed URL or signed cookie */ Builder expirationDate(Instant expirationDate); } private static final class DefaultBuilder implements Builder { private String resourceUrl; private PrivateKey privateKey; private String keyPairId; private Instant expirationDate; private DefaultBuilder() { } private DefaultBuilder(CannedSignerRequest request) { this.resourceUrl = request.resourceUrl; this.privateKey = request.privateKey; this.keyPairId = request.keyPairId; this.expirationDate = request.expirationDate; } @Override public Builder resourceUrl(String resourceUrl) { this.resourceUrl = resourceUrl; return this; } @Override public Builder privateKey(PrivateKey privateKey) { this.privateKey = privateKey; return this; } @Override public Builder privateKey(Path keyFile) throws Exception { this.privateKey = SigningUtils.loadPrivateKey(keyFile); return this; } @Override public Builder keyPairId(String keyPairId) { this.keyPairId = keyPairId; return this; } @Override public Builder expirationDate(Instant expirationDate) { this.expirationDate = expirationDate; return this; } @Override public CannedSignerRequest build() { return new CannedSignerRequest(this); } } }
4,973
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/CustomSignerRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.nio.file.Path; import java.security.PrivateKey; import java.time.Instant; import java.util.Objects; 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.services.cloudfront.internal.utils.SigningUtils; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * Request to generate CloudFront signed URLs or signed cookies with a custom policy */ @Immutable @ThreadSafe @SdkPublicApi public final class CustomSignerRequest implements CloudFrontSignerRequest, ToCopyableBuilder<CustomSignerRequest.Builder, CustomSignerRequest> { private final String resourceUrl; private final PrivateKey privateKey; private final String keyPairId; private final Instant expirationDate; private final Instant activeDate; private final String ipRange; private CustomSignerRequest(DefaultBuilder builder) { this.resourceUrl = builder.resourceUrl; this.privateKey = builder.privateKey; this.keyPairId = builder.keyPairId; this.expirationDate = builder.expirationDate; this.activeDate = builder.activeDate; this.ipRange = builder.ipRange; } /** * Create a builder that can be used to create a {@link CustomSignerRequest} */ public static Builder builder() { return new DefaultBuilder(); } @Override public Builder toBuilder() { return new DefaultBuilder(this); } @Override public String resourceUrl() { return resourceUrl; } @Override public PrivateKey privateKey() { return privateKey; } @Override public String keyPairId() { return keyPairId; } @Override public Instant expirationDate() { return expirationDate; } /** * Returns the active date, before which users will not yet be able to use the signed URL/cookie to access your private * content */ public Instant activeDate() { return activeDate; } /** * Returns the IP range of the users allowed to access your private content */ public String ipRange() { return ipRange; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CustomSignerRequest cookie = (CustomSignerRequest) o; return Objects.equals(resourceUrl, cookie.resourceUrl) && Objects.equals(privateKey, cookie.privateKey) && Objects.equals(keyPairId, cookie.keyPairId) && Objects.equals(expirationDate, cookie.expirationDate) && Objects.equals(activeDate, cookie.activeDate) && Objects.equals(ipRange, cookie.ipRange); } @Override public int hashCode() { int result = resourceUrl != null ? resourceUrl.hashCode() : 0; result = 31 * result + (privateKey != null ? privateKey.hashCode() : 0); result = 31 * result + (keyPairId != null ? keyPairId.hashCode() : 0); result = 31 * result + (expirationDate != null ? expirationDate.hashCode() : 0); result = 31 * result + (activeDate != null ? activeDate.hashCode() : 0); result = 31 * result + (ipRange != null ? ipRange.hashCode() : 0); return result; } @NotThreadSafe @SdkPublicApi public interface Builder extends CopyableBuilder<CustomSignerRequest.Builder, CustomSignerRequest> { /** * Configure the resource URL to be signed * <p> * The URL or path that uniquely identifies a resource within a * distribution. For standard distributions the resource URL will * be <tt>"http://" + distributionName + "/" + objectKey</tt> * (may also include URL parameters. For distributions with the * HTTPS required protocol, the resource URL must start with * <tt>"https://"</tt> */ Builder resourceUrl(String resourceUrl); /** * Configure the private key to be used to sign the policy. * Takes a PrivateKey object directly */ Builder privateKey(PrivateKey privateKey); /** * Configure the private key to be used to sign the policy. * Takes a Path to the key file, and loads it to return a PrivateKey object */ Builder privateKey(Path keyFile) throws Exception; /** * Configure the ID of the key pair stored in the AWS account */ Builder keyPairId(String keyPairId); /** * Configure the expiration date of the signed URL or signed cookie */ Builder expirationDate(Instant expirationDate); /** * Configure the active date of the signed URL or signed cookie - for custom policies (optional field) */ Builder activeDate(Instant activeDate); /** * Configure the IP range of the signed URL or signed cookie - for custom policies (optional field) * <p> * The allowed IP address range of the client making the GET * request, in IPv4 CIDR form (e.g. 192.168.0.1/24). * IPv6 format is not supported. */ Builder ipRange(String ipRange); } private static final class DefaultBuilder implements Builder { private String resourceUrl; private PrivateKey privateKey; private String keyPairId; private Instant expirationDate; private Instant activeDate; private String ipRange; private DefaultBuilder() { } private DefaultBuilder(CustomSignerRequest request) { this.resourceUrl = request.resourceUrl; this.privateKey = request.privateKey; this.keyPairId = request.keyPairId; this.expirationDate = request.expirationDate; this.activeDate = request.activeDate; this.ipRange = request.ipRange; } @Override public Builder resourceUrl(String resourceUrl) { this.resourceUrl = resourceUrl; return this; } @Override public Builder privateKey(PrivateKey privateKey) { this.privateKey = privateKey; return this; } @Override public Builder privateKey(Path keyFile) throws Exception { this.privateKey = SigningUtils.loadPrivateKey(keyFile); return this; } @Override public Builder keyPairId(String keyPairId) { this.keyPairId = keyPairId; return this; } @Override public Builder expirationDate(Instant expirationDate) { this.expirationDate = expirationDate; return this; } @Override public Builder activeDate(Instant activeDate) { this.activeDate = activeDate; return this; } @Override public Builder ipRange(String ipRange) { this.ipRange = ipRange; return this; } @Override public CustomSignerRequest build() { return new CustomSignerRequest(this); } } }
4,974
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/cookie/CookiesForCustomPolicy.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * Base interface class for CloudFront cookies with custom policies */ @SdkPublicApi public interface CookiesForCustomPolicy extends SignedCookie, ToCopyableBuilder<CookiesForCustomPolicy.Builder, CookiesForCustomPolicy> { /** * Returns the cookie policy header value that can be appended to an HTTP GET request * i.e., "CloudFront-Policy=[POLICY_VALUE]" */ String policyHeaderValue(); @NotThreadSafe interface Builder extends CopyableBuilder<CookiesForCustomPolicy.Builder, CookiesForCustomPolicy> { /** * Configure the resource URL */ Builder resourceUrl(String resourceUrl); /** * Configure the cookie signature header value */ Builder signatureHeaderValue(String signatureHeaderValue); /** * Configure the cookie key pair ID header value */ Builder keyPairIdHeaderValue(String keyPairIdHeaderValue); /** * Configure the cookie policy header value */ Builder policyHeaderValue(String policyHeaderValue); } }
4,975
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/cookie/SignedCookie.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.http.SdkHttpRequest; /** * Base interface class for CloudFront signed cookies */ @Immutable @ThreadSafe @SdkPublicApi public interface SignedCookie { String COOKIE = "Cookie"; /** * Returns the resource URL */ String resourceUrl(); /** * Generates an HTTP GET request that can be executed by an HTTP client to access the resource */ SdkHttpRequest createHttpGetRequest(); /** * Returns the cookie signature header value that can be appended to an HTTP GET request * i.e., "CloudFront-Signature=[SIGNATURE_VALUE]" */ String signatureHeaderValue(); /** * Returns the cookie key-pair-Id header value that can be appended to an HTTP GET request * i.e., "CloudFront-Key-Pair-Id=[KEY_PAIR_ID_VALUE]" */ String keyPairIdHeaderValue(); }
4,976
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/cookie/CookiesForCannedPolicy.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * Base interface class for CloudFront cookies with canned policies */ @SdkPublicApi public interface CookiesForCannedPolicy extends SignedCookie, ToCopyableBuilder<CookiesForCannedPolicy.Builder, CookiesForCannedPolicy> { /** * Returns the cookie expires header value that can be appended to an HTTP GET request * i.e., "CloudFront-Expires=[EXPIRES_VALUE]" */ String expiresHeaderValue(); @NotThreadSafe interface Builder extends CopyableBuilder<CookiesForCannedPolicy.Builder, CookiesForCannedPolicy> { /** * Configure the resource URL */ Builder resourceUrl(String resourceUrl); /** * Configure the cookie signature header value */ Builder signatureHeaderValue(String signatureHeaderValue); /** * Configure the cookie key pair ID header value */ Builder keyPairIdHeaderValue(String keyPairIdHeaderValue); /** * Configure the cookie expires header value */ Builder expiresHeaderValue(String expiresHeaderValue); } }
4,977
0
Create_ds/aws-sdk-java-v2/services/glacier/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/glacier/src/test/java/software/amazon/awssdk/services/glacier/UploadArchiveHeaderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.glacier; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.any; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static software.amazon.awssdk.http.Header.CONTENT_TYPE; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.io.File; import java.io.IOException; 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.internal.util.Mimetype; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.glacier.model.UploadArchiveRequest; import software.amazon.awssdk.testutils.RandomTempFile; public class UploadArchiveHeaderTest { @Rule public WireMockRule mockServer = new WireMockRule(0); private GlacierClient glacier; private UploadArchiveRequest request; @Before public void setup() { glacier = GlacierClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_WEST_2).endpointOverride(URI.create(getEndpoint())) .build(); request = UploadArchiveRequest.builder().vaultName("test").build(); } private String getEndpoint() { return "http://localhost:" + mockServer.port(); } @Test public void putObjectBytes_headerShouldContainContentType() { stubFor(any(urlMatching(".*")) .willReturn(aResponse() .withStatus(200) .withBody("{}"))); glacier.uploadArchive(request, RequestBody.fromBytes("test".getBytes())); verify(postRequestedFor(anyUrl()).withHeader(CONTENT_TYPE, equalTo(Mimetype.MIMETYPE_OCTET_STREAM))); } @Test public void uploadArchiveFile_headerShouldContainContentType() throws IOException { File file = new RandomTempFile("test.tsv", 10); stubFor(any(urlMatching(".*")) .willReturn(aResponse() .withStatus(200) .withBody("{}"))); glacier.uploadArchive(request, RequestBody.fromFile(file)); file.delete(); verify(postRequestedFor(anyUrl()).withHeader(CONTENT_TYPE, equalTo("text/tab-separated-values"))); } @Test public void uploadArchiveFile_contentTypeShouldNotBeOverrideIfSet() throws IOException { stubFor(any(urlMatching(".*")) .willReturn(aResponse() .withStatus(200) .withBody("{}"))); request = (UploadArchiveRequest) request.toBuilder().overrideConfiguration(b -> b.putHeader(CONTENT_TYPE, "test")).build(); glacier.uploadArchive(request, RequestBody.fromBytes("test".getBytes())); verify(postRequestedFor(anyUrl()).withHeader(CONTENT_TYPE, equalTo("test"))); } }
4,978
0
Create_ds/aws-sdk-java-v2/services/glacier/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/glacier/src/test/java/software/amazon/awssdk/services/glacier/AccountIdDefaultValueTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.glacier; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.any; 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 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.regions.Region; import software.amazon.awssdk.services.glacier.model.ListVaultsRequest; /** * Glacier has a customization to default accountId to '-' (which indicates the current account) if not provided. */ public class AccountIdDefaultValueTest { @Rule public WireMockRule mockServer = new WireMockRule(0); private GlacierClient glacier; @Before public void setup() { glacier = GlacierClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_WEST_2).endpointOverride(URI.create(getEndpoint())) .build(); } private String getEndpoint() { return "http://localhost:" + mockServer.port(); } @Test public void noAccountIdProvided_DefaultsToHyphen() { stubFor(any(urlMatching(".*")) .willReturn(aResponse() .withStatus(200) .withBody("{}"))); glacier.listVaults(ListVaultsRequest.builder().build()); verify(getRequestedFor(urlEqualTo("/-/vaults"))); } @Test public void accountIdProvided_DoesNotChangeValue() { stubFor(any(urlMatching(".*")) .willReturn(aResponse() .withStatus(200) .withBody("{}"))); glacier.listVaults(ListVaultsRequest.builder().accountId("1234").build()); verify(getRequestedFor(urlEqualTo("/1234/vaults"))); } }
4,979
0
Create_ds/aws-sdk-java-v2/services/glacier/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/glacier/src/it/java/software/amazon/awssdk/services/glacier/ServiceIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.glacier; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.assertj.core.api.Condition; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; 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.services.glacier.model.ListVaultsRequest; import software.amazon.awssdk.services.glacier.model.ResourceNotFoundException; import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase; public class ServiceIntegrationTest extends AwsIntegrationTestBase { private GlacierClient client; private CapturingExecutionInterceptor capturingExecutionInterceptor = new CapturingExecutionInterceptor(); @Before public void setup() { client = GlacierClient.builder() .credentialsProvider(getCredentialsProvider()) .overrideConfiguration(ClientOverrideConfiguration .builder() .addExecutionInterceptor(capturingExecutionInterceptor) .build()) .build(); } /** * API version is a required parameter inserted by the * {@link software.amazon.awssdk.services.glacier.internal.GlacierExecutionInterceptor} */ @Test public void listVaults_SendsApiVersion() { client.listVaults(ListVaultsRequest.builder().build()); assertThat(capturingExecutionInterceptor.beforeTransmission) .is(new Condition<>(r -> r.firstMatchingHeader("x-amz-glacier-version") .orElseThrow(() -> new AssertionError("x-amz-glacier-version header not found")) .equals("2012-06-01"), "Glacier API version is present in header")); } /** * Glacier has a custom field name for it's error code so we make sure that works here. */ @Test public void modeledException_IsUnmarshalledCorrectly() { assertThatThrownBy(() -> client.describeVault(r -> r.vaultName("nope"))) .isInstanceOf(ResourceNotFoundException.class); } public static class CapturingExecutionInterceptor implements ExecutionInterceptor { private SdkHttpRequest beforeTransmission; @Override public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) { this.beforeTransmission = context.httpRequest(); } } }
4,980
0
Create_ds/aws-sdk-java-v2/services/glacier/src/main/java/software/amazon/awssdk/services/glacier
Create_ds/aws-sdk-java-v2/services/glacier/src/main/java/software/amazon/awssdk/services/glacier/internal/AcceptJsonInterceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.glacier.internal; import software.amazon.awssdk.annotations.SdkInternalApi; 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; @SdkInternalApi public final class AcceptJsonInterceptor implements ExecutionInterceptor { @Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { return context.httpRequest() .toBuilder() .putHeader("Accept", "application/json") .build(); } }
4,981
0
Create_ds/aws-sdk-java-v2/services/glacier/src/main/java/software/amazon/awssdk/services/glacier
Create_ds/aws-sdk-java-v2/services/glacier/src/main/java/software/amazon/awssdk/services/glacier/internal/GlacierExecutionInterceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.glacier.internal; import software.amazon.awssdk.annotations.SdkInternalApi; 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.services.glacier.model.DescribeJobRequest; import software.amazon.awssdk.services.glacier.model.GetJobOutputRequest; import software.amazon.awssdk.services.glacier.model.UploadMultipartPartRequest; import software.amazon.awssdk.utils.StringUtils; @SdkInternalApi public final class GlacierExecutionInterceptor implements ExecutionInterceptor { @Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { SdkHttpRequest request = context.httpRequest(); Object originalRequest = context.request(); return request.toBuilder() .applyMutation(b -> beforeRequest(originalRequest, b)) .build(); } private SdkHttpRequest.Builder beforeRequest(Object originalRequest, SdkHttpRequest.Builder mutableRequest) { mutableRequest.putHeader("x-amz-glacier-version", "2012-06-01"); // "x-amz-content-sha256" header is required for sig v4 for some streaming operations mutableRequest.putHeader("x-amz-content-sha256", "required"); if (originalRequest instanceof UploadMultipartPartRequest) { mutableRequest.firstMatchingHeader("Content-Range") .ifPresent(range -> mutableRequest.putHeader("Content-Length", Long.toString(parseContentLengthFromRange(range)))); } else if (originalRequest instanceof GetJobOutputRequest || originalRequest instanceof DescribeJobRequest) { String resourcePath = mutableRequest.encodedPath(); if (resourcePath != null) { String newResourcePath = StringUtils.replace(resourcePath, "{jobType}", "archive-retrievals"); mutableRequest.encodedPath(newResourcePath); } } return mutableRequest; } private long parseContentLengthFromRange(String range) { if (range.startsWith("bytes=") || range.startsWith("bytes ")) { range = range.substring(6); } String start = range.substring(0, range.indexOf('-')); String end = range.substring(range.indexOf('-') + 1); if (end.contains("/")) { end = end.substring(0, end.indexOf('/')); } return Long.parseLong(end) - Long.parseLong(start) + 1; } }
4,982
0
Create_ds/aws-sdk-java-v2/services/glacier/src/main/java/software/amazon/awssdk/services/glacier
Create_ds/aws-sdk-java-v2/services/glacier/src/main/java/software/amazon/awssdk/services/glacier/transform/DefaultAccountIdSupplier.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.glacier.transform; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkInternalApi; @SdkInternalApi public final class DefaultAccountIdSupplier { /** * Value that indicates the current account. */ private static final String CURRENT_ACCOUNT_ID = "-"; private static final Supplier<String> INSTANCE = () -> CURRENT_ACCOUNT_ID; private DefaultAccountIdSupplier() { } public static Supplier<String> getInstance() { return INSTANCE; } }
4,983
0
Create_ds/aws-sdk-java-v2/services/elasticbeanstalk/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/elasticbeanstalk/src/it/java/software/amazon/awssdk/services/elasticbeanstalk/ElasticBeanstalkIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.elasticbeanstalk; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static software.amazon.awssdk.testutils.SdkAsserts.assertNotEmpty; import java.util.List; import org.junit.Test; import software.amazon.awssdk.services.elasticbeanstalk.model.ListAvailableSolutionStacksRequest; /** * Integration test to bring up a new ElasticBeanstalk environment and run through as * many operations as possible. */ public class ElasticBeanstalkIntegrationTest extends ElasticBeanstalkIntegrationTestBase { /** Tests that we can describe the available solution stacks. */ @Test public void testListAvailableSolutionStacks() throws Exception { List<String> solutionStacks = elasticbeanstalk.listAvailableSolutionStacks(ListAvailableSolutionStacksRequest.builder().build()) .solutionStacks(); assertNotNull(solutionStacks); assertTrue(solutionStacks.size() > 1); for (String stack : solutionStacks) { assertNotEmpty(stack); } } }
4,984
0
Create_ds/aws-sdk-java-v2/services/elasticbeanstalk/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/elasticbeanstalk/src/it/java/software/amazon/awssdk/services/elasticbeanstalk/ElasticBeanstalkIntegrationTestBase.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.elasticbeanstalk; import java.io.IOException; import org.junit.BeforeClass; import software.amazon.awssdk.testutils.service.AwsTestBase; /** * Base class for ElasticBeanstalk integration tests; responsible for loading AWS account info for * running the tests, and instantiating clients for tests to use. */ public abstract class ElasticBeanstalkIntegrationTestBase extends AwsTestBase { protected static ElasticBeanstalkClient elasticbeanstalk; /** * Loads the AWS account info for the integration tests and creates an clients for tests to use. */ @BeforeClass public static void setUp() throws IOException { setUpCredentials(); elasticbeanstalk = ElasticBeanstalkClient.builder() .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .build(); } }
4,985
0
Create_ds/aws-sdk-java-v2/services/cloudsearchdomain/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/services/cloudsearchdomain/src/test/java/software/amazon/awssdk/cloudsearchdomain/SearchRequestUnitTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.cloudsearchdomain; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; 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 com.github.tomakehurst.wiremock.common.ConsoleNotifier; import com.github.tomakehurst.wiremock.core.WireMockConfiguration; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.io.IOException; 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.regions.Region; import software.amazon.awssdk.services.cloudsearchdomain.CloudSearchDomainClient; import software.amazon.awssdk.services.cloudsearchdomain.model.SearchRequest; /** * Unit tests for {@link SearchRequest}. */ public class SearchRequestUnitTest { private static final AwsBasicCredentials CREDENTIALS = AwsBasicCredentials.create("access", "secret"); @Rule public WireMockRule wireMockRule = new WireMockRule(new WireMockConfiguration().port(0).notifier(new ConsoleNotifier(true))); private CloudSearchDomainClient searchClient; @Before public void testSetup() { searchClient = CloudSearchDomainClient.builder() .credentialsProvider(StaticCredentialsProvider.create(CREDENTIALS)) .region(Region.US_EAST_1) .endpointOverride(URI.create("http://localhost:" + wireMockRule.port())) .build(); } /** * Test that search requests use POST instead of (the also supported) GET. * @throws IOException */ @Test public void testPostUsedForSearchRequest() throws IOException { stubFor(post(urlMatching("/.*")) .willReturn(aResponse() .withStatus(200) .withBody("{\"status\":{\"rid\":\"fooBar\",\"time-ms\":7},\"hits\":{\"found\":0,\"start\":0,\"hit\":[]}}"))); searchClient.search(SearchRequest.builder().query("Lord of the Rings").build()); verify(postRequestedFor(urlEqualTo("/2013-01-01/search")) .withRequestBody(equalTo("format=sdk&pretty=true&q=Lord+of+the+Rings")) .withHeader("Content-Type", equalTo("application/x-www-form-urlencoded"))); } }
4,986
0
Create_ds/aws-sdk-java-v2/services/cloudsearchdomain/src/main/java/software/amazon/awssdk/services/cloudsearchdomain
Create_ds/aws-sdk-java-v2/services/cloudsearchdomain/src/main/java/software/amazon/awssdk/services/cloudsearchdomain/internal/SwitchToPostInterceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.cloudsearchdomain.internal; import static java.util.Collections.singletonList; import static software.amazon.awssdk.utils.StringUtils.lowerCase; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; 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; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.services.cloudsearchdomain.model.SearchRequest; /** * Ensures that all SearchRequests use <code>POST</code> instead of <code>GET</code>, moving the query parameters to be form data. */ @SdkInternalApi public final class SwitchToPostInterceptor implements ExecutionInterceptor { @Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { SdkHttpRequest httpRequest = context.httpRequest(); if (context.request() instanceof SearchRequest) { return httpRequest.toBuilder() .clearQueryParameters() .method(SdkHttpMethod.POST) .putHeader("Content-Type", singletonList("application/x-www-form-urlencoded")) .build(); } return context.httpRequest(); } @Override public Optional<RequestBody> modifyHttpContent(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { if (context.request() instanceof SearchRequest) { byte[] params = context.httpRequest().encodedQueryParametersAsFormData().orElse("") .getBytes(StandardCharsets.UTF_8); return Optional.of(RequestBody.fromContentProvider(() -> new ByteArrayInputStream(params), params.length, "application/x-www-form-urlencoded; charset=" + lowerCase(StandardCharsets.UTF_8.toString()))); } return context.requestBody(); } }
4,987
0
Create_ds/aws-sdk-java-v2/services/neptune/src/test/java/software/amazon/awssdk/services/neptune
Create_ds/aws-sdk-java-v2/services/neptune/src/test/java/software/amazon/awssdk/services/neptune/internal/PresignRequestWireMockTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.neptune.internal; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import org.junit.Before; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.neptune.NeptuneClient; import java.net.URI; import java.util.List; import static com.github.tomakehurst.wiremock.client.WireMock.*; import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; @RunWith(MockitoJUnitRunner.class) public class PresignRequestWireMockTest { @ClassRule public static final WireMockRule WIRE_MOCK = new WireMockRule(0); public static NeptuneClient client; @BeforeClass public static void setup() { client = NeptuneClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_EAST_1) .endpointOverride(URI.create("http://localhost:" + WIRE_MOCK.port())) .build(); } @Before public void reset() { WIRE_MOCK.resetAll(); } @Test public void copyDbClusterSnapshotWithSourceRegionSendsPresignedUrl() { verifyMethodCallSendsPresignedUrl(() -> client.copyDBClusterSnapshot(r -> r.sourceRegion("us-west-2")), "CopyDBClusterSnapshot"); } @Test public void copyDBSnapshotWithSourceRegionSendsPresignedUrl() { verifyMethodCallSendsPresignedUrl(() -> client.copyDBClusterSnapshot(r -> r.sourceRegion("us-west-2")), "CopyDBClusterSnapshot"); } @Test public void createDbClusterWithSourceRegionSendsPresignedUrl() { verifyMethodCallSendsPresignedUrl(() -> client.createDBCluster(r -> r.sourceRegion("us-west-2")), "CreateDBCluster"); } @Test public void createDBInstanceReadReplicaWithSourceRegionSendsPresignedUrl() { verifyMethodCallSendsPresignedUrl(() -> client.createDBCluster(r -> r.sourceRegion("us-west-2")), "CreateDBCluster"); } public void verifyMethodCallSendsPresignedUrl(Runnable methodCall, String actionName) { stubFor(any(anyUrl()).willReturn(aResponse().withStatus(200).withBody("<body/>"))); methodCall.run(); List<LoggedRequest> requests = findAll(anyRequestedFor(anyUrl())); assertThat(requests).isNotEmpty(); LoggedRequest lastRequest = requests.get(0); String lastRequestBody = new String(lastRequest.getBody(), UTF_8); assertThat(lastRequestBody).contains("PreSignedUrl=https%3A%2F%2Frds.us-west-2.amazonaws.com%3FAction%3D" + actionName + "%26Version%3D2014-10-31%26DestinationRegion%3Dus-east-1%26"); } }
4,988
0
Create_ds/aws-sdk-java-v2/services/neptune/src/test/java/software/amazon/awssdk/services/neptune
Create_ds/aws-sdk-java-v2/services/neptune/src/test/java/software/amazon/awssdk/services/neptune/internal/PresignRequestHandlerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.neptune.internal; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.when; import java.net.URI; import java.net.URISyntaxException; import java.time.Clock; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.TimeZone; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute; import software.amazon.awssdk.awscore.endpoint.DefaultServiceEndpointBuilder; import software.amazon.awssdk.core.Protocol; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.interceptor.InterceptorContext; import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.neptune.model.CopyDbClusterSnapshotRequest; import software.amazon.awssdk.services.neptune.model.NeptuneRequest; import software.amazon.awssdk.services.neptune.transform.CopyDbClusterSnapshotRequestMarshaller; /** * Unit Tests for {@link RdsPresignInterceptor} */ public class PresignRequestHandlerTest { private static final AwsBasicCredentials CREDENTIALS = AwsBasicCredentials.create("foo", "bar"); private static final Region DESTINATION_REGION = Region.of("us-west-2"); private static final RdsPresignInterceptor<CopyDbClusterSnapshotRequest> presignInterceptor = new CopyDbClusterSnapshotPresignInterceptor(); private final CopyDbClusterSnapshotRequestMarshaller marshaller = new CopyDbClusterSnapshotRequestMarshaller(RdsPresignInterceptor.PROTOCOL_FACTORY); @Test public void testSetsPresignedUrl() { CopyDbClusterSnapshotRequest request = makeTestRequest(); SdkHttpRequest presignedRequest = modifyHttpRequest(presignInterceptor, request, marshallRequest(request)); assertNotNull(presignedRequest.rawQueryParameters().get("PreSignedUrl").get(0)); } @Test public void testComputesPresignedUrlCorrectlyForCopyDbClusterSnapshotRequest() { // Note: test data was baselined by performing actual calls, with real // credentials to RDS and checking that they succeeded. Then the // request was recreated with all the same parameters but with test // credentials. final CopyDbClusterSnapshotRequest request = CopyDbClusterSnapshotRequest.builder() .sourceDBClusterSnapshotIdentifier("arn:aws:rds:us-east-1:123456789012:snapshot:rds:test-instance-ss-2016-12-20-23-19") .targetDBClusterSnapshotIdentifier("test-instance-ss-copy-2") .sourceRegion("us-east-1") .kmsKeyId("arn:aws:kms:us-west-2:123456789012:key/11111111-2222-3333-4444-555555555555") .build(); Calendar c = new GregorianCalendar(); c.setTimeZone(TimeZone.getTimeZone("UTC")); // 20161221T180735Z // Note: month is 0-based c.set(2016, Calendar.DECEMBER, 21, 18, 7, 35); Clock signingDateOverride = Mockito.mock(Clock.class); when(signingDateOverride.millis()).thenReturn(c.getTimeInMillis()); RdsPresignInterceptor<CopyDbClusterSnapshotRequest> interceptor = new CopyDbClusterSnapshotPresignInterceptor(signingDateOverride); SdkHttpRequest presignedRequest = modifyHttpRequest(interceptor, request, marshallRequest(request)); final String expectedPreSignedUrl = "https://rds.us-east-1.amazonaws.com?" + "Action=CopyDBClusterSnapshot" + "&Version=2014-10-31" + "&SourceDBClusterSnapshotIdentifier=arn%3Aaws%3Ards%3Aus-east-1%3A123456789012%3Asnapshot%3Ards%3Atest-instance-ss-2016-12-20-23-19" + "&TargetDBClusterSnapshotIdentifier=test-instance-ss-copy-2" + "&KmsKeyId=arn%3Aaws%3Akms%3Aus-west-2%3A123456789012%3Akey%2F11111111-2222-3333-4444-555555555555" + "&DestinationRegion=us-west-2" + "&X-Amz-Algorithm=AWS4-HMAC-SHA256" + "&X-Amz-Date=20161221T180735Z" + "&X-Amz-SignedHeaders=host" + "&X-Amz-Expires=604800" + "&X-Amz-Credential=foo%2F20161221%2Fus-east-1%2Frds%2Faws4_request" + "&X-Amz-Signature=00822ebbba95e2e6ac09112aa85621fbef060a596e3e1480f9f4ac61493e9821"; assertEquals(expectedPreSignedUrl, presignedRequest.rawQueryParameters().get("PreSignedUrl").get(0)); } @Test public void testSkipsPresigningIfUrlSet() { CopyDbClusterSnapshotRequest request = CopyDbClusterSnapshotRequest.builder() .sourceRegion("us-west-2") .preSignedUrl("PRESIGNED") .build(); SdkHttpRequest presignedRequest = modifyHttpRequest(presignInterceptor, request, marshallRequest(request)); assertEquals("PRESIGNED", presignedRequest.rawQueryParameters().get("PreSignedUrl").get(0)); } @Test public void testSkipsPresigningIfSourceRegionNotSet() { CopyDbClusterSnapshotRequest request = CopyDbClusterSnapshotRequest.builder().build(); SdkHttpRequest presignedRequest = modifyHttpRequest(presignInterceptor, request, marshallRequest(request)); assertNull(presignedRequest.rawQueryParameters().get("PreSignedUrl")); } @Test public void testParsesDestinationRegionfromRequestEndpoint() throws URISyntaxException { CopyDbClusterSnapshotRequest request = CopyDbClusterSnapshotRequest.builder() .sourceRegion("us-east-1") .build(); Region destination = Region.of("us-west-2"); SdkHttpFullRequest marshalled = marshallRequest(request); final SdkHttpRequest presignedRequest = modifyHttpRequest(presignInterceptor, request, marshalled); final URI presignedUrl = new URI(presignedRequest.rawQueryParameters().get("PreSignedUrl").get(0)); assertTrue(presignedUrl.toString().contains("DestinationRegion=" + destination.id())); } @Test public void testSourceRegionRemovedFromOriginalRequest() { CopyDbClusterSnapshotRequest request = makeTestRequest(); SdkHttpFullRequest marshalled = marshallRequest(request); SdkHttpRequest actual = modifyHttpRequest(presignInterceptor, request, marshalled); assertFalse(actual.rawQueryParameters().containsKey("SourceRegion")); } private SdkHttpFullRequest marshallRequest(CopyDbClusterSnapshotRequest request) { SdkHttpFullRequest.Builder marshalled = marshaller.marshall(request).toBuilder(); URI endpoint = new DefaultServiceEndpointBuilder("rds", Protocol.HTTPS.toString()) .withRegion(DESTINATION_REGION) .getServiceEndpoint(); return marshalled.uri(endpoint).build(); } private ExecutionAttributes executionAttributes() { return new ExecutionAttributes().putAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS, CREDENTIALS) .putAttribute(AwsSignerExecutionAttribute.SIGNING_REGION, DESTINATION_REGION) .putAttribute(SdkExecutionAttribute.PROFILE_FILE_SUPPLIER, ProfileFile::defaultProfileFile) .putAttribute(SdkExecutionAttribute.PROFILE_NAME, "default"); } private CopyDbClusterSnapshotRequest makeTestRequest() { return CopyDbClusterSnapshotRequest.builder() .sourceDBClusterSnapshotIdentifier("arn:aws:rds:us-east-1:123456789012:snapshot:rds:test-instance-ss-2016-12-20-23-19") .targetDBClusterSnapshotIdentifier("test-instance-ss-copy-2") .sourceRegion("us-east-1") .kmsKeyId("arn:aws:kms:us-west-2:123456789012:key/11111111-2222-3333-4444-555555555555") .build(); } private SdkHttpRequest modifyHttpRequest(ExecutionInterceptor interceptor, NeptuneRequest request, SdkHttpFullRequest httpRequest) { InterceptorContext context = InterceptorContext.builder().request(request).httpRequest(httpRequest).build(); return interceptor.modifyHttpRequest(context, executionAttributes()); } }
4,989
0
Create_ds/aws-sdk-java-v2/services/neptune/src/main/java/software/amazon/awssdk/services/neptune
Create_ds/aws-sdk-java-v2/services/neptune/src/main/java/software/amazon/awssdk/services/neptune/internal/CopyDbClusterSnapshotPresignInterceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.neptune.internal; import java.time.Clock; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkTestInternalApi; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.services.neptune.model.CopyDbClusterSnapshotRequest; import software.amazon.awssdk.services.neptune.transform.CopyDbClusterSnapshotRequestMarshaller; /** * Handler for pre-signing {@link CopyDbClusterSnapshotRequest}. */ @SdkInternalApi public final class CopyDbClusterSnapshotPresignInterceptor extends RdsPresignInterceptor<CopyDbClusterSnapshotRequest> { public static final CopyDbClusterSnapshotRequestMarshaller MARSHALLER = new CopyDbClusterSnapshotRequestMarshaller(PROTOCOL_FACTORY); public CopyDbClusterSnapshotPresignInterceptor() { super(CopyDbClusterSnapshotRequest.class); } @SdkTestInternalApi CopyDbClusterSnapshotPresignInterceptor(Clock signingDateOverride) { super(CopyDbClusterSnapshotRequest.class, signingDateOverride); } @Override protected PresignableRequest adaptRequest(final CopyDbClusterSnapshotRequest originalRequest) { return new PresignableRequest() { @Override public String getSourceRegion() { return originalRequest.sourceRegion(); } @Override public SdkHttpFullRequest marshall() { return MARSHALLER.marshall(originalRequest); } }; } }
4,990
0
Create_ds/aws-sdk-java-v2/services/neptune/src/main/java/software/amazon/awssdk/services/neptune
Create_ds/aws-sdk-java-v2/services/neptune/src/main/java/software/amazon/awssdk/services/neptune/internal/CreateDbClusterPresignInterceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.neptune.internal; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.services.neptune.model.CreateDbClusterRequest; import software.amazon.awssdk.services.neptune.transform.CreateDbClusterRequestMarshaller; /** * Handler for pre-signing {@link CreateDbClusterRequest}. */ @SdkInternalApi public final class CreateDbClusterPresignInterceptor extends RdsPresignInterceptor<CreateDbClusterRequest> { public static final CreateDbClusterRequestMarshaller MARSHALLER = new CreateDbClusterRequestMarshaller(PROTOCOL_FACTORY); public CreateDbClusterPresignInterceptor() { super(CreateDbClusterRequest.class); } @Override protected PresignableRequest adaptRequest(final CreateDbClusterRequest originalRequest) { return new PresignableRequest() { @Override public String getSourceRegion() { return originalRequest.sourceRegion(); } @Override public SdkHttpFullRequest marshall() { return MARSHALLER.marshall(originalRequest); } }; } }
4,991
0
Create_ds/aws-sdk-java-v2/services/neptune/src/main/java/software/amazon/awssdk/services/neptune
Create_ds/aws-sdk-java-v2/services/neptune/src/main/java/software/amazon/awssdk/services/neptune/internal/RdsPresignInterceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.neptune.internal; import static software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute.AWS_CREDENTIALS; import static software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME; import java.net.URI; import java.time.Clock; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.auth.credentials.AwsCredentials; import software.amazon.awssdk.auth.credentials.CredentialUtils; import software.amazon.awssdk.auth.signer.Aws4Signer; import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute; import software.amazon.awssdk.auth.signer.params.Aws4PresignerParams; import software.amazon.awssdk.awscore.AwsExecutionAttribute; import software.amazon.awssdk.awscore.endpoint.DefaultServiceEndpointBuilder; import software.amazon.awssdk.core.Protocol; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.core.exception.SdkClientException; 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.interceptor.SdkExecutionAttribute; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.protocols.query.AwsQueryProtocolFactory; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.neptune.model.NeptuneRequest; import software.amazon.awssdk.utils.CompletableFutureUtils; /** * Abstract pre-sign handler that follows the pre-signing scheme outlined in the 'RDS Presigned URL for Cross-Region Copying' * SEP. * * @param <T> The request type. */ @SdkInternalApi public abstract class RdsPresignInterceptor<T extends NeptuneRequest> implements ExecutionInterceptor { private static final URI CUSTOM_ENDPOINT_LOCALHOST = URI.create("http://localhost"); protected static final AwsQueryProtocolFactory PROTOCOL_FACTORY = AwsQueryProtocolFactory .builder() // Need an endpoint to marshall but this will be overwritten in modifyHttpRequest .clientConfiguration(SdkClientConfiguration.builder() .option(SdkClientOption.ENDPOINT, CUSTOM_ENDPOINT_LOCALHOST) .build()) .build(); private static final String SERVICE_NAME = "rds"; private static final String PARAM_SOURCE_REGION = "SourceRegion"; private static final String PARAM_DESTINATION_REGION = "DestinationRegion"; private static final String PARAM_PRESIGNED_URL = "PreSignedUrl"; public interface PresignableRequest { String getSourceRegion(); SdkHttpFullRequest marshall(); } private final Class<T> requestClassToPreSign; private final Clock signingOverrideClock; protected RdsPresignInterceptor(Class<T> requestClassToPreSign) { this(requestClassToPreSign, null); } protected RdsPresignInterceptor(Class<T> requestClassToPreSign, Clock signingOverrideClock) { this.requestClassToPreSign = requestClassToPreSign; this.signingOverrideClock = signingOverrideClock; } @Override public final SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { SdkHttpRequest request = context.httpRequest(); SdkRequest originalRequest = context.request(); if (!requestClassToPreSign.isInstance(originalRequest)) { return request; } if (request.firstMatchingRawQueryParameter(PARAM_PRESIGNED_URL).isPresent()) { return request; } PresignableRequest presignableRequest = adaptRequest(requestClassToPreSign.cast(originalRequest)); String sourceRegion = presignableRequest.getSourceRegion(); if (sourceRegion == null) { return request; } String destinationRegion = executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNING_REGION).id(); URI endpoint = createEndpoint(sourceRegion, SERVICE_NAME, executionAttributes); SdkHttpFullRequest.Builder marshalledRequest = presignableRequest.marshall().toBuilder().uri(endpoint); SdkHttpFullRequest requestToPresign = marshalledRequest.method(SdkHttpMethod.GET) .putRawQueryParameter(PARAM_DESTINATION_REGION, destinationRegion) .removeQueryParameter(PARAM_SOURCE_REGION) .build(); requestToPresign = presignRequest(requestToPresign, executionAttributes, sourceRegion); String presignedUrl = requestToPresign.getUri().toString(); return request.toBuilder() .putRawQueryParameter(PARAM_PRESIGNED_URL, presignedUrl) // Remove the unmodeled params to stop them getting onto the wire .removeQueryParameter(PARAM_SOURCE_REGION) .build(); } /** * Adapts the request to the {@link PresignableRequest}. * * @param originalRequest the original request * @return a PresignableRequest */ protected abstract PresignableRequest adaptRequest(T originalRequest); private SdkHttpFullRequest presignRequest(SdkHttpFullRequest request, ExecutionAttributes attributes, String signingRegion) { Aws4Signer signer = Aws4Signer.create(); Aws4PresignerParams presignerParams = Aws4PresignerParams.builder() .signingRegion(Region.of(signingRegion)) .signingName(SERVICE_NAME) .signingClockOverride(signingOverrideClock) .awsCredentials(resolveCredentials(attributes)) .build(); return signer.presign(request, presignerParams); } private AwsCredentials resolveCredentials(ExecutionAttributes attributes) { return attributes.getOptionalAttribute(SELECTED_AUTH_SCHEME) .map(selectedAuthScheme -> selectedAuthScheme.identity()) .map(identityFuture -> CompletableFutureUtils.joinLikeSync(identityFuture)) .filter(identity -> identity instanceof AwsCredentialsIdentity) .map(identity -> { AwsCredentialsIdentity awsCredentialsIdentity = (AwsCredentialsIdentity) identity; return CredentialUtils.toCredentials(awsCredentialsIdentity); }).orElse(attributes.getAttribute(AWS_CREDENTIALS)); } private URI createEndpoint(String regionName, String serviceName, ExecutionAttributes attributes) { Region region = Region.of(regionName); if (region == null) { throw SdkClientException.builder() .message("{" + serviceName + ", " + regionName + "} was not " + "found in region metadata. Update to latest version of SDK and try again.") .build(); } return new DefaultServiceEndpointBuilder(SERVICE_NAME, Protocol.HTTPS.toString()) .withRegion(region) .withProfileFile(attributes.getAttribute(SdkExecutionAttribute.PROFILE_FILE_SUPPLIER)) .withProfileName(attributes.getAttribute(SdkExecutionAttribute.PROFILE_NAME)) .withDualstackEnabled(attributes.getAttribute(AwsExecutionAttribute.DUALSTACK_ENDPOINT_ENABLED)) .withFipsEnabled(attributes.getAttribute(AwsExecutionAttribute.FIPS_ENDPOINT_ENABLED)) .getServiceEndpoint(); } }
4,992
0
Create_ds/aws-sdk-java-v2/services/ecr/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/ecr/src/it/java/software/amazon/awssdk/services/ecr/EcrIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.ecr; import junit.framework.Assert; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.services.ecr.model.CreateRepositoryRequest; import software.amazon.awssdk.services.ecr.model.CreateRepositoryResponse; import software.amazon.awssdk.services.ecr.model.DeleteRepositoryRequest; import software.amazon.awssdk.services.ecr.model.DescribeRepositoriesRequest; import software.amazon.awssdk.services.ecr.model.Repository; import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase; public class EcrIntegrationTest extends AwsIntegrationTestBase { private static final String REPO_NAME = "java-sdk-test-repo-" + System.currentTimeMillis(); private static EcrClient ecr; @BeforeClass public static void setUpClient() throws Exception { ecr = EcrClient.builder().credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build(); } @AfterClass public static void tearDownAfterClass() throws Exception { if (ecr != null) { ecr.deleteRepository(DeleteRepositoryRequest.builder() .repositoryName(REPO_NAME) .build()); } } @Test public void basicTest() { CreateRepositoryResponse result = ecr.createRepository( CreateRepositoryRequest.builder() .repositoryName(REPO_NAME) .build()); Assert.assertNotNull(result.repository()); Assert.assertEquals(result.repository().repositoryName(), REPO_NAME); Assert.assertNotNull(result.repository().repositoryArn()); Assert.assertNotNull(result.repository().registryId()); String repoArn = result.repository().repositoryArn(); String registryId = result.repository().registryId(); Repository repo = ecr.describeRepositories(DescribeRepositoriesRequest.builder() .repositoryNames(REPO_NAME) .build()) .repositories().get(0); Assert.assertEquals(repo.registryId(), registryId); Assert.assertEquals(repo.repositoryName(), REPO_NAME); Assert.assertEquals(repo.repositoryArn(), repoArn); } }
4,993
0
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/utils/test
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/utils/test/util/DynamoDBTestBase.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package utils.test.util; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.math.BigDecimal; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest; import software.amazon.awssdk.services.dynamodb.model.TableDescription; import software.amazon.awssdk.services.dynamodb.model.TableStatus; import software.amazon.awssdk.testutils.service.AwsTestBase; import software.amazon.awssdk.utils.Logger; public class DynamoDBTestBase extends AwsTestBase { protected static final String ENDPOINT = "http://dynamodb.us-east-1.amazonaws.com/"; protected static final Region REGION = Region.US_EAST_1; protected static DynamoDbClient dynamo; protected static DynamoDbAsyncClient dynamoAsync; private static final Logger log = Logger.loggerFor(DynamoDBTestBase.class); public static void setUpTestBase() { try { setUpCredentials(); } catch (Exception e) { throw SdkClientException.builder().message("Unable to load credential property file.").cause(e).build(); } dynamo = DynamoDbClient.builder().region(REGION).credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build(); dynamoAsync = DynamoDbAsyncClient.builder().region(REGION).credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build(); } public static DynamoDbClient getClient() { if (dynamo == null) { setUpTestBase(); } return dynamo; } protected static void waitForTableToBecomeDeleted(String tableName) { waitForTableToBecomeDeleted(dynamo, tableName); } public static void waitForTableToBecomeDeleted(DynamoDbClient dynamo, String tableName) { log.info(() -> "Waiting for " + tableName + " to become Deleted..."); long startTime = System.currentTimeMillis(); long endTime = startTime + (60_000); while (System.currentTimeMillis() < endTime) { try { Thread.sleep(5_000); } catch (Exception e) { // Ignored or expected. } try { DescribeTableRequest request = DescribeTableRequest.builder().tableName(tableName).build(); TableDescription table = dynamo.describeTable(request).table(); log.info(() -> " - current state: " + table.tableStatusAsString()); if (table.tableStatus() == TableStatus.DELETING) { continue; } } catch (AwsServiceException exception) { if (exception.awsErrorDetails().errorCode().equalsIgnoreCase("ResourceNotFoundException")) { log.info(() -> "successfully deleted"); return; } } } throw new RuntimeException("Table " + tableName + " never went deleted"); } protected static <T extends Object> void assertSetsEqual(Collection<T> expected, Collection<T> given) { Set<T> givenCopy = new HashSet<T>(); givenCopy.addAll(given); for (T e : expected) { if (!givenCopy.remove(e)) { fail("Expected element not found: " + e); } } assertTrue("Unexpected elements found: " + givenCopy, givenCopy.isEmpty()); } /** * Only valid for whole numbers */ protected static void assertNumericSetsEquals(Set<? extends Number> expected, Collection<String> given) { Set<BigDecimal> givenCopy = new HashSet<BigDecimal>(); for (String s : given) { BigDecimal bd = new BigDecimal(s); givenCopy.add(bd.setScale(0)); } Set<BigDecimal> expectedCopy = new HashSet<BigDecimal>(); for (Number n : expected) { BigDecimal bd = new BigDecimal(n.toString()); expectedCopy.add(bd.setScale(0)); } assertSetsEqual(expectedCopy, givenCopy); } protected static <T extends Object> Set<T> toSet(T... array) { Set<T> set = new HashSet<T>(); for (T t : array) { set.add(t); } return set; } protected static <T extends Object> Set<T> toSet(Collection<T> collection) { Set<T> set = new HashSet<T>(); for (T t : collection) { set.add(t); } return set; } protected static byte[] generateByteArray(int length) { byte[] bytes = new byte[length]; for (int i = 0; i < length; i++) { bytes[i] = (byte) (i % Byte.MAX_VALUE); } return bytes; } /** * Gets a map of key values for the single hash key attribute value given. */ protected Map<String, AttributeValue> mapKey(String attributeName, AttributeValue value) { HashMap<String, AttributeValue> map = new HashMap<String, AttributeValue>(); map.put(attributeName, value); return map; } }
4,994
0
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/utils/test
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/utils/test/util/DynamoDBIntegrationTestBase.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package utils.test.util; import org.junit.BeforeClass; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition; import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement; import software.amazon.awssdk.services.dynamodb.model.KeyType; import software.amazon.awssdk.services.dynamodb.model.ListTablesRequest; import software.amazon.awssdk.services.dynamodb.model.ListTablesResponse; import software.amazon.awssdk.services.dynamodb.model.LocalSecondaryIndex; import software.amazon.awssdk.services.dynamodb.model.Projection; import software.amazon.awssdk.services.dynamodb.model.ProjectionType; import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput; import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType; public class DynamoDBIntegrationTestBase extends DynamoDBTestBase { protected static final String KEY_NAME = "key"; protected static final String TABLE_NAME = "aws-java-sdk-util"; protected static final String TABLE_WITH_RANGE_ATTRIBUTE = "aws-java-sdk-range-test"; protected static final String TABLE_WITH_INDEX_RANGE_ATTRIBUTE = "aws-java-sdk-index-range-test"; protected static long startKey = System.currentTimeMillis(); @BeforeClass public static void setUp() throws Exception { setUpCredentials(); dynamo = DynamoDbClient.builder().region(Region.US_EAST_1).credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build(); // Create a table String keyName = KEY_NAME; CreateTableRequest createTableRequest = CreateTableRequest.builder() .tableName(TABLE_NAME) .keySchema(KeySchemaElement.builder() .attributeName(keyName) .keyType(KeyType.HASH) .build()) .attributeDefinitions( AttributeDefinition.builder().attributeName(keyName) .attributeType(ScalarAttributeType.S) .build()) .provisionedThroughput(ProvisionedThroughput.builder() .readCapacityUnits(10L) .writeCapacityUnits(5L).build()) .build(); if (TableUtils.createTableIfNotExists(dynamo, createTableRequest)) { TableUtils.waitUntilActive(dynamo, TABLE_NAME); } } /** * Quick utility method to delete all tables when we have too much capacity * reserved for the region. */ public static void deleteAllTables() { ListTablesResponse listTables = dynamo.listTables(ListTablesRequest.builder().build()); for (String name : listTables.tableNames()) { dynamo.deleteTable(DeleteTableRequest.builder().tableName(name).build()); } } protected static void setUpTableWithRangeAttribute() throws Exception { setUp(); String keyName = DynamoDBIntegrationTestBase.KEY_NAME; String rangeKeyAttributeName = "rangeKey"; CreateTableRequest createTableRequest = CreateTableRequest.builder() .tableName(TABLE_WITH_RANGE_ATTRIBUTE) .keySchema( KeySchemaElement.builder() .attributeName(keyName) .keyType(KeyType.HASH) .build(), KeySchemaElement.builder() .attributeName(rangeKeyAttributeName) .keyType(KeyType.RANGE) .build()) .attributeDefinitions( AttributeDefinition.builder() .attributeName(keyName) .attributeType(ScalarAttributeType.N) .build(), AttributeDefinition.builder() .attributeName(rangeKeyAttributeName) .attributeType(ScalarAttributeType.N) .build()) .provisionedThroughput(ProvisionedThroughput.builder() .readCapacityUnits(10L) .writeCapacityUnits(5L).build()) .build(); if (TableUtils.createTableIfNotExists(dynamo, createTableRequest)) { TableUtils.waitUntilActive(dynamo, TABLE_WITH_RANGE_ATTRIBUTE); } } protected static void setUpTableWithIndexRangeAttribute(boolean recreateTable) throws Exception { setUp(); if (recreateTable) { dynamo.deleteTable(DeleteTableRequest.builder().tableName(TABLE_WITH_INDEX_RANGE_ATTRIBUTE).build()); waitForTableToBecomeDeleted(TABLE_WITH_INDEX_RANGE_ATTRIBUTE); } String keyName = DynamoDBIntegrationTestBase.KEY_NAME; String rangeKeyAttributeName = "rangeKey"; String indexFooRangeKeyAttributeName = "indexFooRangeKey"; String indexBarRangeKeyAttributeName = "indexBarRangeKey"; String multipleIndexRangeKeyAttributeName = "multipleIndexRangeKey"; String fooAttributeName = "fooAttribute"; String barAttributeName = "barAttribute"; String indexFooName = "index_foo"; String indexBarName = "index_bar"; String indexFooCopyName = "index_foo_copy"; String indexBarCopyName = "index_bar_copy"; CreateTableRequest createTableRequest = CreateTableRequest.builder() .tableName(TABLE_WITH_INDEX_RANGE_ATTRIBUTE) .keySchema( KeySchemaElement.builder() .attributeName(keyName) .keyType(KeyType.HASH) .build(), KeySchemaElement.builder() .attributeName(rangeKeyAttributeName) .keyType(KeyType.RANGE) .build()) .localSecondaryIndexes( LocalSecondaryIndex.builder() .indexName(indexFooName) .keySchema( KeySchemaElement.builder() .attributeName(keyName) .keyType(KeyType.HASH) .build(), KeySchemaElement.builder() .attributeName(indexFooRangeKeyAttributeName) .keyType(KeyType.RANGE) .build()) .projection(Projection.builder() .projectionType(ProjectionType.INCLUDE) .nonKeyAttributes(fooAttributeName) .build()) .build(), LocalSecondaryIndex.builder() .indexName(indexBarName) .keySchema( KeySchemaElement.builder() .attributeName(keyName) .keyType(KeyType.HASH) .build(), KeySchemaElement.builder() .attributeName(indexBarRangeKeyAttributeName) .keyType(KeyType.RANGE) .build()) .projection(Projection.builder() .projectionType(ProjectionType.INCLUDE) .nonKeyAttributes(barAttributeName) .build()) .build(), LocalSecondaryIndex.builder() .indexName(indexFooCopyName) .keySchema( KeySchemaElement.builder() .attributeName(keyName) .keyType(KeyType.HASH) .build(), KeySchemaElement.builder() .attributeName(multipleIndexRangeKeyAttributeName) .keyType(KeyType.RANGE) .build()) .projection(Projection.builder() .projectionType(ProjectionType.INCLUDE) .nonKeyAttributes(fooAttributeName) .build()) .build(), LocalSecondaryIndex.builder() .indexName(indexBarCopyName) .keySchema( KeySchemaElement.builder() .attributeName(keyName) .keyType(KeyType.HASH) .build(), KeySchemaElement.builder() .attributeName(multipleIndexRangeKeyAttributeName) .keyType(KeyType.RANGE) .build()) .projection(Projection.builder() .projectionType(ProjectionType.INCLUDE) .nonKeyAttributes(barAttributeName) .build()) .build()) .attributeDefinitions( AttributeDefinition.builder().attributeName(keyName).attributeType(ScalarAttributeType.N).build(), AttributeDefinition.builder().attributeName(rangeKeyAttributeName) .attributeType(ScalarAttributeType.N).build(), AttributeDefinition.builder().attributeName(indexFooRangeKeyAttributeName) .attributeType(ScalarAttributeType.N).build(), AttributeDefinition.builder().attributeName(indexBarRangeKeyAttributeName) .attributeType(ScalarAttributeType.N).build(), AttributeDefinition.builder().attributeName(multipleIndexRangeKeyAttributeName) .attributeType(ScalarAttributeType.N).build()) .provisionedThroughput(ProvisionedThroughput.builder() .readCapacityUnits(10L) .writeCapacityUnits(5L).build()) .build(); if (TableUtils.createTableIfNotExists(dynamo, createTableRequest)) { TableUtils.waitUntilActive(dynamo, TABLE_WITH_INDEX_RANGE_ATTRIBUTE); } } }
4,995
0
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/utils/test
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/utils/test/util/TableUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package utils.test.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest; import software.amazon.awssdk.services.dynamodb.model.ResourceInUseException; import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException; import software.amazon.awssdk.services.dynamodb.model.TableDescription; import software.amazon.awssdk.services.dynamodb.model.TableStatus; /** * Utility methods for working with DynamoDB tables. * * <pre class="brush: java"> * // ... create DynamoDB table ... * try { * waitUntilActive(dynamoDB, myTableName()); * } catch (SdkClientException e) { * // table didn't become active * } * // ... start making calls to table ... * </pre> */ public class TableUtils { private static final int DEFAULT_WAIT_TIMEOUT = 20 * 60 * 1000; private static final int DEFAULT_WAIT_INTERVAL = 10 * 1000; /** * The logging utility. */ private static final Logger log = LoggerFactory.getLogger(TableUtils.class); /** * Waits up to 10 minutes for a specified DynamoDB table to resolve, * indicating that it exists. If the table doesn't return a result after * this time, a SdkClientException is thrown. * * @param dynamo * The DynamoDB client to use to make requests. * @param tableName * The name of the table being resolved. * * @throws SdkClientException * If the specified table does not resolve before this method * times out and stops polling. * @throws InterruptedException * If the thread is interrupted while waiting for the table to * resolve. */ public static void waitUntilExists(final DynamoDbClient dynamo, final String tableName) throws InterruptedException { waitUntilExists(dynamo, tableName, DEFAULT_WAIT_TIMEOUT, DEFAULT_WAIT_INTERVAL); } /** * Waits up to a specified amount of time for a specified DynamoDB table to * resolve, indicating that it exists. If the table doesn't return a result * after this time, a SdkClientException is thrown. * * @param dynamo * The DynamoDB client to use to make requests. * @param tableName * The name of the table being resolved. * @param timeout * The maximum number of milliseconds to wait. * @param interval * The poll interval in milliseconds. * * @throws SdkClientException * If the specified table does not resolve before this method * times out and stops polling. * @throws InterruptedException * If the thread is interrupted while waiting for the table to * resolve. */ public static void waitUntilExists(final DynamoDbClient dynamo, final String tableName, final int timeout, final int interval) throws InterruptedException { TableDescription table = waitForTableDescription(dynamo, tableName, null, timeout, interval); if (table == null) { throw SdkClientException.builder().message("Table " + tableName + " never returned a result").build(); } } /** * Waits up to 10 minutes for a specified DynamoDB table to move into the * <code>ACTIVE</code> state. If the table does not exist or does not * transition to the <code>ACTIVE</code> state after this time, then * SdkClientException is thrown. * * @param dynamo * The DynamoDB client to use to make requests. * @param tableName * The name of the table whose status is being checked. * * @throws TableNeverTransitionedToStateException * If the specified table does not exist or does not transition * into the <code>ACTIVE</code> state before this method times * out and stops polling. * @throws InterruptedException * If the thread is interrupted while waiting for the table to * transition into the <code>ACTIVE</code> state. */ public static void waitUntilActive(final DynamoDbClient dynamo, final String tableName) throws InterruptedException, TableNeverTransitionedToStateException { waitUntilActive(dynamo, tableName, DEFAULT_WAIT_TIMEOUT, DEFAULT_WAIT_INTERVAL); } /** * Waits up to a specified amount of time for a specified DynamoDB table to * move into the <code>ACTIVE</code> state. If the table does not exist or * does not transition to the <code>ACTIVE</code> state after this time, * then a SdkClientException is thrown. * * @param dynamo * The DynamoDB client to use to make requests. * @param tableName * The name of the table whose status is being checked. * @param timeout * The maximum number of milliseconds to wait. * @param interval * The poll interval in milliseconds. * * @throws TableNeverTransitionedToStateException * If the specified table does not exist or does not transition * into the <code>ACTIVE</code> state before this method times * out and stops polling. * @throws InterruptedException * If the thread is interrupted while waiting for the table to * transition into the <code>ACTIVE</code> state. */ public static void waitUntilActive(final DynamoDbClient dynamo, final String tableName, final int timeout, final int interval) throws InterruptedException, TableNeverTransitionedToStateException { TableDescription table = waitForTableDescription(dynamo, tableName, TableStatus.ACTIVE, timeout, interval); if (table == null || !table.tableStatus().equals(TableStatus.ACTIVE)) { throw new TableNeverTransitionedToStateException(tableName, TableStatus.ACTIVE); } } /** * Wait for the table to reach the desired status and returns the table * description * * @param dynamo * Dynamo client to use * @param tableName * Table name to poll status of * @param desiredStatus * Desired {@link TableStatus} to wait for. If null this method * simply waits until DescribeTable returns something non-null * (i.e. any status) * @param timeout * Timeout in milliseconds to continue to poll for desired status * @param interval * Time to wait in milliseconds between poll attempts * @return Null if DescribeTables never returns a result, otherwise the * result of the last poll attempt (which may or may not have the * desired state) * @throws {@link * IllegalArgumentException} If timeout or interval is invalid */ private static TableDescription waitForTableDescription(final DynamoDbClient dynamo, final String tableName, TableStatus desiredStatus, final int timeout, final int interval) throws InterruptedException, IllegalArgumentException { if (timeout < 0) { throw new IllegalArgumentException("Timeout must be >= 0"); } if (interval <= 0 || interval >= timeout) { throw new IllegalArgumentException("Interval must be > 0 and < timeout"); } long startTime = System.currentTimeMillis(); long endTime = startTime + timeout; TableDescription table = null; while (System.currentTimeMillis() < endTime) { try { table = dynamo.describeTable(DescribeTableRequest.builder().tableName(tableName).build()).table(); if (desiredStatus == null || table.tableStatus().equals(desiredStatus)) { return table; } } catch (ResourceNotFoundException rnfe) { // ResourceNotFound means the table doesn't exist yet, // so ignore this error and just keep polling. } Thread.sleep(interval); } return table; } /** * Creates the table and ignores any errors if it already exists. * @param dynamo The Dynamo client to use. * @param createTableRequest The create table request. * @return True if created, false otherwise. */ public static boolean createTableIfNotExists(final DynamoDbClient dynamo, final CreateTableRequest createTableRequest) { try { dynamo.createTable(createTableRequest); return true; } catch (final ResourceInUseException e) { if (log.isTraceEnabled()) { log.trace("Table " + createTableRequest.tableName() + " already exists", e); } } return false; } /** * Deletes the table and ignores any errors if it doesn't exist. * @param dynamo The Dynamo client to use. * @param deleteTableRequest The delete table request. * @return True if deleted, false otherwise. */ public static boolean deleteTableIfExists(final DynamoDbClient dynamo, final DeleteTableRequest deleteTableRequest) { try { dynamo.deleteTable(deleteTableRequest); return true; } catch (final ResourceNotFoundException e) { if (log.isTraceEnabled()) { log.trace("Table " + deleteTableRequest.tableName() + " does not exist", e); } } return false; } /** * Thrown by {@link TableUtils} when a table never reaches a desired state */ public static class TableNeverTransitionedToStateException extends SdkClientException { private static final long serialVersionUID = 8920567021104846647L; public TableNeverTransitionedToStateException(String tableName, TableStatus desiredStatus) { super(SdkClientException.builder() .message("Table " + tableName + " never transitioned to desired state of " + desiredStatus.toString())); } } }
4,996
0
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/utils/test
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/utils/test/resources/DynamoDBTableResource.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package utils.test.resources; import java.util.List; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest; import software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndex; import software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndexDescription; import software.amazon.awssdk.services.dynamodb.model.LocalSecondaryIndex; import software.amazon.awssdk.services.dynamodb.model.LocalSecondaryIndexDescription; import software.amazon.awssdk.services.dynamodb.model.Projection; import software.amazon.awssdk.services.dynamodb.model.TableDescription; import software.amazon.awssdk.services.dynamodb.model.TableStatus; import software.amazon.awssdk.testutils.UnorderedCollectionComparator; import software.amazon.awssdk.utils.Logger; import utils.resources.TestResource; import utils.test.util.DynamoDBTestBase; import utils.test.util.TableUtils; public abstract class DynamoDBTableResource implements TestResource { private static final Logger log = Logger.loggerFor(DynamoDBTableResource.class); /** * Returns true if the two lists of GlobalSecondaryIndex and * GlobalSecondaryIndexDescription share the same set of: * 1) indexName * 2) projection * 3) keySchema (compared as unordered lists) */ static boolean equalUnorderedGsiLists(List<GlobalSecondaryIndex> listA, List<GlobalSecondaryIndexDescription> listB) { return UnorderedCollectionComparator.equalUnorderedCollections( listA, listB, new UnorderedCollectionComparator.CrossTypeComparator<GlobalSecondaryIndex, GlobalSecondaryIndexDescription>() { @Override public boolean equals(GlobalSecondaryIndex a, GlobalSecondaryIndexDescription b) { return a.indexName().equals(b.indexName()) && equalProjections(a.projection(), b.projection()) && UnorderedCollectionComparator.equalUnorderedCollections(a.keySchema(), b.keySchema()); } }); } /** * Returns true if the two lists of LocalSecondaryIndex and * LocalSecondaryIndexDescription share the same set of: * 1) indexName * 2) projection * 3) keySchema (compared as unordered lists) */ static boolean equalUnorderedLsiLists(List<LocalSecondaryIndex> listA, List<LocalSecondaryIndexDescription> listB) { return UnorderedCollectionComparator.equalUnorderedCollections( listA, listB, new UnorderedCollectionComparator.CrossTypeComparator<LocalSecondaryIndex, LocalSecondaryIndexDescription>() { @Override public boolean equals(LocalSecondaryIndex a, LocalSecondaryIndexDescription b) { // Project parameter might not be specified in the // CreateTableRequest. But it should be treated as equal // to the default projection type - KEYS_ONLY. return a.indexName().equals(b.indexName()) && equalProjections(a.projection(), b.projection()) && UnorderedCollectionComparator.equalUnorderedCollections(a.keySchema(), b.keySchema()); } }); } /** * Compares the Projection parameter included in the CreateTableRequest, * with the one returned from DescribeTableResponse. */ static boolean equalProjections(Projection fromCreateTableRequest, Projection fromDescribeTableResponse) { if (fromCreateTableRequest == null || fromDescribeTableResponse == null) { throw new IllegalStateException("The projection parameter should never be null."); } return fromCreateTableRequest.projectionType().equals( fromDescribeTableResponse.projectionType()) && UnorderedCollectionComparator.equalUnorderedCollections( fromCreateTableRequest.nonKeyAttributes(), fromDescribeTableResponse.nonKeyAttributes()); } protected abstract DynamoDbClient getClient(); protected abstract CreateTableRequest getCreateTableRequest(); /** * Implementation of TestResource interfaces */ @Override public void create(boolean waitTillFinished) { log.info(() -> "Creating " + this + "..."); getClient().createTable(getCreateTableRequest()); if (waitTillFinished) { log.info(() -> "Waiting for " + this + " to become active..."); try { TableUtils.waitUntilActive(getClient(), getCreateTableRequest().tableName()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } @Override public void delete(boolean waitTillFinished) { log.info(() -> "Deleting " + this + "..."); getClient().deleteTable(DeleteTableRequest.builder().tableName(getCreateTableRequest().tableName()).build()); if (waitTillFinished) { log.info(() -> "Waiting for " + this + " to become deleted..."); DynamoDBTestBase.waitForTableToBecomeDeleted(getClient(), getCreateTableRequest().tableName()); } } @Override public ResourceStatus getResourceStatus() { CreateTableRequest createRequest = getCreateTableRequest(); TableDescription table; try { table = getClient().describeTable(DescribeTableRequest.builder().tableName( createRequest.tableName()).build()).table(); } catch (AwsServiceException exception) { if (exception.awsErrorDetails().errorCode().equalsIgnoreCase("ResourceNotFoundException")) { return ResourceStatus.NOT_EXIST; } throw exception; } if (table.tableStatus() == TableStatus.ACTIVE) { // returns AVAILABLE only if table KeySchema + LSIs + GSIs all match. if (UnorderedCollectionComparator.equalUnorderedCollections(createRequest.keySchema(), table.keySchema()) && equalUnorderedGsiLists(createRequest.globalSecondaryIndexes(), table.globalSecondaryIndexes()) && equalUnorderedLsiLists(createRequest.localSecondaryIndexes(), table.localSecondaryIndexes())) { return ResourceStatus.AVAILABLE; } else { return ResourceStatus.EXIST_INCOMPATIBLE_RESOURCE; } } else if (table.tableStatus() == TableStatus.CREATING || table.tableStatus() == TableStatus.UPDATING || table.tableStatus() == TableStatus.DELETING) { return ResourceStatus.TRANSIENT; } else { return ResourceStatus.NOT_EXIST; } } /** * Object interfaces */ @Override public String toString() { return "DynamoDB Table [" + getCreateTableRequest().tableName() + "]"; } @Override public int hashCode() { return getCreateTableRequest().hashCode(); } @Override public boolean equals(Object other) { if (!(other instanceof DynamoDBTableResource)) { return false; } return getCreateTableRequest().equals( ((DynamoDBTableResource) other).getCreateTableRequest()); } }
4,997
0
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/utils
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/utils/resources/TestResourceUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package utils.resources; import java.time.Duration; import software.amazon.awssdk.testutils.Waiter; import software.amazon.awssdk.utils.Logger; import utils.resources.RequiredResources.ResourceCreationPolicy; import utils.resources.TestResource.ResourceStatus; public class TestResourceUtils { private static final Logger log = Logger.loggerFor(TestResourceUtils.class); public static void createResource(TestResource resource, ResourceCreationPolicy policy) throws InterruptedException { TestResource.ResourceStatus finalizedStatus = waitForFinalizedStatus(resource); if (policy == ResourceCreationPolicy.ALWAYS_RECREATE) { if (finalizedStatus != ResourceStatus.NOT_EXIST) { resource.delete(true); } resource.create(true); } else if (policy == ResourceCreationPolicy.REUSE_EXISTING) { switch (finalizedStatus) { case AVAILABLE: log.info(() -> "Found existing resource " + resource + " that could be reused..."); return; case EXIST_INCOMPATIBLE_RESOURCE: resource.delete(true); resource.create(true); // fallthru case NOT_EXIST: resource.create(true); break; default: break; } } } public static void deleteResource(TestResource resource) throws InterruptedException { ResourceStatus finalizedStatus = waitForFinalizedStatus(resource); if (finalizedStatus != ResourceStatus.NOT_EXIST) { resource.delete(false); } } public static ResourceStatus waitForFinalizedStatus(TestResource resource) throws InterruptedException { return Waiter.run(resource::getResourceStatus) .until(s -> s != ResourceStatus.TRANSIENT) .orFailAfter(Duration.ofMinutes(10)); } }
4,998
0
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/utils
Create_ds/aws-sdk-java-v2/services/dynamodb/src/test/java/utils/resources/ResourceCentricBlockJUnit4ClassRunner.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package utils.resources; import java.util.HashSet; import java.util.Set; import org.junit.jupiter.api.Disabled; import org.junit.runner.Description; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunNotifier; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.InitializationError; import org.junit.runners.model.Statement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import utils.resources.RequiredResources.RequiredResource; import utils.resources.RequiredResources.ResourceRetentionPolicy; public class ResourceCentricBlockJUnit4ClassRunner extends BlockJUnit4ClassRunner { private final Set<TestResource> resourcesToBeDestroyedAfterAllTests; private final RequiredResources classRequiredResourcesAnnotation; private final Logger log = LoggerFactory.getLogger(ResourceCentricBlockJUnit4ClassRunner.class); public ResourceCentricBlockJUnit4ClassRunner(Class<?> klass) throws InitializationError { super(klass); classRequiredResourcesAnnotation = klass.getAnnotation(RequiredResources.class); resourcesToBeDestroyedAfterAllTests = new HashSet<TestResource>(); } /** * */ private static TestResource createResourceInstance(RequiredResource resourceAnnotation) throws InstantiationException, IllegalAccessException { Class<? extends TestResource> resourceClazz = resourceAnnotation.resource(); if (resourceClazz == null) { throw new IllegalArgumentException( "resource parameter is missing for the @RequiredResource annotation."); } return resourceClazz.newInstance(); } @Override protected void runChild(final FrameworkMethod method, RunNotifier notifier) { Description description = describeChild(method); if (method.getAnnotation(Disabled.class) != null) { notifier.fireTestIgnored(description); } else { RequiredResources annotation = method.getAnnotation(RequiredResources.class); if (annotation != null) { try { beforeRunLeaf(annotation.value()); } catch (Exception e) { notifier.fireTestFailure(new Failure(description, e)); } } runLeaf(methodBlock(method), description, notifier); if (annotation != null) { try { afterRunLeaf(annotation.value()); } catch (Exception e) { notifier.fireTestFailure(new Failure(description, e)); } } } } /** * Override the withBeforeClasses method to inject executing resource * creation between @BeforeClass methods and test methods. */ @Override protected Statement withBeforeClasses(final Statement statement) { Statement withRequiredResourcesCreation = new Statement() { @Override public void evaluate() throws Throwable { if (classRequiredResourcesAnnotation != null) { beforeRunClass(classRequiredResourcesAnnotation.value()); } statement.evaluate(); } }; return super.withBeforeClasses(withRequiredResourcesCreation); } /** * Override the withAfterClasses method to inject executing resource * creation between test methods and the @AfterClass methods. */ @Override protected Statement withAfterClasses(final Statement statement) { Statement withRequiredResourcesDeletion = new Statement() { @Override public void evaluate() throws Throwable { statement.evaluate(); afterRunClass(); } }; return super.withAfterClasses(withRequiredResourcesDeletion); } private void beforeRunClass(RequiredResource[] resourcesAnnotation) throws InstantiationException, IllegalAccessException, InterruptedException { log.debug("Processing @RequiredResources before running the test class..."); for (RequiredResource resourceAnnotation : resourcesAnnotation) { TestResource resource = createResourceInstance(resourceAnnotation); TestResourceUtils.createResource(resource, resourceAnnotation.creationPolicy()); if (resourceAnnotation.retentionPolicy() != ResourceRetentionPolicy.KEEP) { resourcesToBeDestroyedAfterAllTests.add(resource); } } } private void afterRunClass() throws InstantiationException, IllegalAccessException, InterruptedException { log.debug("Processing @RequiredResources after running the test class..."); for (TestResource resource : resourcesToBeDestroyedAfterAllTests) { TestResourceUtils.deleteResource(resource); } } private void beforeRunLeaf(RequiredResource[] resourcesAnnotation) throws InstantiationException, IllegalAccessException, InterruptedException { log.debug("Processing @RequiredResources before running the test..."); for (RequiredResource resourceAnnotation : resourcesAnnotation) { TestResource resource = createResourceInstance(resourceAnnotation); TestResourceUtils.createResource(resource, resourceAnnotation.creationPolicy()); if (resourceAnnotation.retentionPolicy() == ResourceRetentionPolicy.DESTROY_AFTER_ALL_TESTS) { resourcesToBeDestroyedAfterAllTests.add(resource); } } } private void afterRunLeaf(RequiredResource[] resourcesAnnotation) throws InstantiationException, IllegalAccessException, InterruptedException { log.debug("Processing @RequiredResources after running the test..."); for (RequiredResource resourceAnnotation : resourcesAnnotation) { TestResource resource = createResourceInstance(resourceAnnotation); if (resourceAnnotation.retentionPolicy() == ResourceRetentionPolicy.DESTROY_IMMEDIATELY) { TestResourceUtils.deleteResource(resource); } } } }
4,999