This is an automated email from the ASF dual-hosted git repository.
adoroszlai pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/ozone.git
The following commit(s) were added to refs/heads/master by this push:
new 703e935e75e HDDS-17649. Enforce source ETag preconditions for
UploadPartCopy (#11898)
703e935e75e is described below
commit 703e935e75eb8c922dfa446db70405186692b500
Author: Andy Huang <[email protected]>
AuthorDate: Fri Nov 20 17:45:58 2026 +0800
HDDS-17649. Enforce source ETag preconditions for UploadPartCopy (#11898)
---
.../ozone/s3/awssdk/v2/AbstractS3SDKV2Tests.java | 57 ++++++++++-
.../hadoop/ozone/s3/endpoint/ObjectEndpoint.java | 15 +--
.../ozone/s3/endpoint/S3ConditionalRequest.java | 60 ++---------
.../s3/endpoint/TestMultipartUploadWithCopy.java | 114 ++++++++++++++++++++-
.../hadoop/ozone/s3/endpoint/TestObjectGet.java | 2 +-
.../s3/endpoint/TestS3ConditionalRequest.java | 92 +++++++++++++++++
6 files changed, 270 insertions(+), 70 deletions(-)
diff --git
a/hadoop-ozone/integration-test-s3/src/test/java/org/apache/hadoop/ozone/s3/awssdk/v2/AbstractS3SDKV2Tests.java
b/hadoop-ozone/integration-test-s3/src/test/java/org/apache/hadoop/ozone/s3/awssdk/v2/AbstractS3SDKV2Tests.java
index 54ea5826d4b..805c077033d 100644
---
a/hadoop-ozone/integration-test-s3/src/test/java/org/apache/hadoop/ozone/s3/awssdk/v2/AbstractS3SDKV2Tests.java
+++
b/hadoop-ozone/integration-test-s3/src/test/java/org/apache/hadoop/ozone/s3/awssdk/v2/AbstractS3SDKV2Tests.java
@@ -120,6 +120,7 @@
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
@@ -1109,12 +1110,25 @@ public void
testGetObjectIfModifiedSinceReturnsNotModified() {
S3Exception exception = assertThrows(S3Exception.class,
() -> s3Client.getObjectAsBytes(
b -> b.bucket(bucketName).key(keyName)
- .ifModifiedSince(headObjectResponse.lastModified()
- .plusSeconds(60))));
+ .ifModifiedSince(headObjectResponse.lastModified())));
assertEquals(304, exception.statusCode());
}
+ @Test
+ public void testGetObjectIfModifiedSinceFutureDateIsIgnored() {
+ final String bucketName = getBucketName();
+ final String keyName = getKeyName();
+ final String content = "bar";
+ s3Client.createBucket(b -> b.bucket(bucketName));
+ s3Client.putObject(b -> b.bucket(bucketName).key(keyName),
RequestBody.fromString(content));
+
+ ResponseBytes<GetObjectResponse> response = s3Client.getObjectAsBytes(
+ b ->
b.bucket(bucketName).key(keyName).ifModifiedSince(Instant.now().plusSeconds(86400)));
+
+ assertEquals(content, response.asUtf8String());
+ }
+
/**
* Adapted from ceph s3-tests test_object_read_unreadable.
*/
@@ -2608,6 +2622,45 @@ public void testCopyObjectWithDestinationIfMatchFail() {
assertEquals("PreconditionFailed",
exception.awsErrorDetails().errorCode());
}
+ @ParameterizedTest
+ @CsvSource({"match, true, false", "match, false, true", "none-match, true,
true", "none-match, false, false"})
+ public void testUploadPartCopySourceETag(String condition, boolean matching,
boolean rejected) {
+ final String bucketName = getBucketName();
+ final String sourceKey = getKeyName("source");
+ final String destKey = getKeyName("dest");
+ s3Client.createBucket(b -> b.bucket(bucketName));
+ final String sourceETag = s3Client.putObject(b ->
b.bucket(bucketName).key(sourceKey),
+ RequestBody.fromString("copy-source-content")).eTag();
+ final String uploadId = s3Client.createMultipartUpload(b ->
b.bucket(bucketName).key(destKey)).uploadId();
+ try {
+ UploadPartCopyRequest.Builder request = UploadPartCopyRequest.builder()
+ .sourceBucket(bucketName)
+ .sourceKey(sourceKey)
+ .destinationBucket(bucketName)
+ .destinationKey(destKey)
+ .uploadId(uploadId)
+ .partNumber(1);
+ String conditionalETag = matching ? sourceETag : "\"wrong-etag\"";
+ if ("match".equals(condition)) {
+ request.copySourceIfMatch(conditionalETag);
+ } else {
+ request.copySourceIfNoneMatch(conditionalETag);
+ }
+ if (rejected) {
+ S3Exception exception = assertThrows(S3Exception.class, () ->
s3Client.uploadPartCopy(request.build()));
+ assertEquals(412, exception.statusCode());
+ assertEquals("PreconditionFailed",
exception.awsErrorDetails().errorCode());
+ assertTrue(s3Client.listParts(b ->
b.bucket(bucketName).key(destKey).uploadId(uploadId)).parts().isEmpty());
+ } else {
+ UploadPartCopyResponse response =
s3Client.uploadPartCopy(request.build());
+ assertEquals(sourceETag, response.copyPartResult().eTag());
+ assertEquals(1, s3Client.listParts(b ->
b.bucket(bucketName).key(destKey).uploadId(uploadId)).parts().size());
+ }
+ } finally {
+ s3Client.abortMultipartUpload(b ->
b.bucket(bucketName).key(destKey).uploadId(uploadId));
+ }
+ }
+
@Test
public void testUploadPartCopyInvalidRange() {
final String sourceBucketName = getBucketName("source");
diff --git
a/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/endpoint/ObjectEndpoint.java
b/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/endpoint/ObjectEndpoint.java
index 802bd8c4ac6..7aa8cac1bba 100644
---
a/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/endpoint/ObjectEndpoint.java
+++
b/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/endpoint/ObjectEndpoint.java
@@ -31,8 +31,6 @@
import static org.apache.hadoop.ozone.s3.util.S3Consts.CONTENT_RANGE_HEADER;
import static org.apache.hadoop.ozone.s3.util.S3Consts.COPY_SOURCE_HEADER;
import static
org.apache.hadoop.ozone.s3.util.S3Consts.COPY_SOURCE_HEADER_RANGE;
-import static
org.apache.hadoop.ozone.s3.util.S3Consts.COPY_SOURCE_IF_MODIFIED_SINCE;
-import static
org.apache.hadoop.ozone.s3.util.S3Consts.COPY_SOURCE_IF_UNMODIFIED_SINCE;
import static
org.apache.hadoop.ozone.s3.util.S3Consts.CUSTOM_METADATA_COPY_DIRECTIVE_HEADER;
import static org.apache.hadoop.ozone.s3.util.S3Consts.CopyDirective;
import static
org.apache.hadoop.ozone.s3.util.S3Consts.DECODED_CONTENT_LENGTH_HEADER;
@@ -1031,17 +1029,8 @@ uploadID, getChunkSize(), multiDigestInputStream, perf,
getHeaders(),
} else {
length = sourceKeyDetails.getDataSize();
}
- Long sourceKeyModificationTime = sourceKeyDetails
- .getModificationTime().toEpochMilli();
- String copySourceIfModifiedSince =
- getHeaders().getHeaderString(COPY_SOURCE_IF_MODIFIED_SINCE);
- String copySourceIfUnmodifiedSince =
- getHeaders().getHeaderString(COPY_SOURCE_IF_UNMODIFIED_SINCE);
- if (!S3ConditionalRequest.checkCopySourceModificationTime(
- sourceKeyModificationTime,
- copySourceIfModifiedSince, copySourceIfUnmodifiedSince)) {
- throw newError(PRECOND_FAILED, sourceBucket + "/" + sourceKey);
- }
+ S3ConditionalRequest.evaluatePreconditions(getHeaders(), sourceBucket
+ "/" + sourceKey,
+ sourceKeyDetails,
S3ConditionalRequest.PreconditionContext.COPY_SOURCE);
final MessageDigest md5Digest = getMD5DigestInstance();
try (OzoneInputStream sourceObject = sourceKeyDetails.getContent();
diff --git
a/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/endpoint/S3ConditionalRequest.java
b/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/endpoint/S3ConditionalRequest.java
index b93c06b4554..a9d25910f9c 100644
---
a/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/endpoint/S3ConditionalRequest.java
+++
b/hadoop-ozone/s3gateway/src/main/java/org/apache/hadoop/ozone/s3/endpoint/S3ConditionalRequest.java
@@ -25,7 +25,6 @@
import java.text.ParseException;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
-import java.util.OptionalLong;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
@@ -61,7 +60,7 @@ enum PreconditionContext {
S3Consts.IF_UNMODIFIED_SINCE_HEADER),
/**
- * For CopyObject source validation. Always throws 412 Precondition Failed
+ * For CopyObject and UploadPartCopy source validation. Always throws 412
Precondition Failed
* when any condition is not met (no 304 responses).
*/
COPY_SOURCE(
@@ -131,27 +130,6 @@ static Response evaluatePreconditions(HttpHeaders headers,
return null;
}
- static boolean checkCopySourceModificationTime(Long lastModificationTime,
- String copySourceIfModifiedSinceStr,
- String copySourceIfUnmodifiedSinceStr) {
- long copySourceIfModifiedSince = Long.MIN_VALUE;
- long copySourceIfUnmodifiedSince = Long.MAX_VALUE;
-
- OptionalLong modifiedDate =
- parseAndValidatePastOrPresentDate(copySourceIfModifiedSinceStr);
- if (modifiedDate.isPresent()) {
- copySourceIfModifiedSince = modifiedDate.getAsLong();
- }
-
- OptionalLong unmodifiedDate =
- parseAndValidatePastOrPresentDate(copySourceIfUnmodifiedSinceStr);
- if (unmodifiedDate.isPresent()) {
- copySourceIfUnmodifiedSince = unmodifiedDate.getAsLong();
- }
- return (copySourceIfModifiedSince <= lastModificationTime)
- && (lastModificationTime <= copySourceIfUnmodifiedSince);
- }
-
static WriteConditions parseWriteConditions(HttpHeaders headers,
String keyPath) throws OS3Exception {
String ifNoneMatch =
headers.getHeaderString(S3Consts.IF_NONE_MATCH_HEADER);
@@ -216,8 +194,7 @@ private static boolean eTagMatches(String headerValue,
String currentETag) {
return false;
}
- private static boolean matchesIfModifiedSince(OzoneKey key,
- String headerValue) {
+ private static boolean matchesIfModifiedSince(OzoneKey key, String
headerValue) {
Instant since = parseConditionalInstant(headerValue);
if (since == null) {
return true;
@@ -227,14 +204,12 @@ private static boolean matchesIfModifiedSince(OzoneKey
key,
return lastModified.isAfter(since);
}
- private static boolean matchesIfUnmodifiedSince(OzoneKey key,
- String headerValue) {
+ private static boolean matchesIfUnmodifiedSince(OzoneKey key, String
headerValue) {
Instant since = parseConditionalInstant(headerValue);
if (since == null) {
return true;
}
- Instant lastModified = key.getModificationTime()
- .truncatedTo(ChronoUnit.SECONDS);
+ Instant lastModified =
key.getModificationTime().truncatedTo(ChronoUnit.SECONDS);
return !lastModified.isAfter(since);
}
@@ -243,33 +218,16 @@ private static Instant parseConditionalInstant(String
headerValue) {
return null;
}
try {
- return Instant.ofEpochMilli(OzoneUtils.formatDate(headerValue))
- .truncatedTo(ChronoUnit.SECONDS);
+ Instant since = Instant.ofEpochMilli(OzoneUtils.formatDate(headerValue));
+ if (since.isAfter(Instant.now())) {
+ return null;
+ }
+ return since.truncatedTo(ChronoUnit.SECONDS);
} catch (IllegalArgumentException | ParseException ex) {
return null;
}
}
- private static OptionalLong parseAndValidatePastOrPresentDate(
- String ozoneDateStr) {
- if (ozoneDateStr == null) {
- return OptionalLong.empty();
- }
-
- long ozoneDateInMs;
- try {
- ozoneDateInMs = OzoneUtils.formatDate(ozoneDateStr);
- } catch (ParseException e) {
- return OptionalLong.empty();
- }
-
- long currentDate = System.currentTimeMillis();
- if (ozoneDateInMs <= currentDate) {
- return OptionalLong.of(ozoneDateInMs);
- }
- return OptionalLong.empty();
- }
-
static final class WriteConditions {
private final String ifNoneMatch;
private final String ifMatch;
diff --git
a/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/endpoint/TestMultipartUploadWithCopy.java
b/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/endpoint/TestMultipartUploadWithCopy.java
index d53950ac182..6c9ab233886 100644
---
a/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/endpoint/TestMultipartUploadWithCopy.java
+++
b/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/endpoint/TestMultipartUploadWithCopy.java
@@ -25,12 +25,15 @@
import static org.apache.hadoop.ozone.s3.endpoint.EndpointTestUtils.uploadPart;
import static org.apache.hadoop.ozone.s3.util.S3Consts.COPY_SOURCE_HEADER;
import static
org.apache.hadoop.ozone.s3.util.S3Consts.COPY_SOURCE_HEADER_RANGE;
+import static org.apache.hadoop.ozone.s3.util.S3Consts.COPY_SOURCE_IF_MATCH;
import static
org.apache.hadoop.ozone.s3.util.S3Consts.COPY_SOURCE_IF_MODIFIED_SINCE;
+import static org.apache.hadoop.ozone.s3.util.S3Consts.COPY_SOURCE_IF_PREFIX;
import static
org.apache.hadoop.ozone.s3.util.S3Consts.COPY_SOURCE_IF_UNMODIFIED_SINCE;
import static org.apache.hadoop.ozone.s3.util.S3Consts.STORAGE_CLASS_HEADER;
import static org.apache.hadoop.ozone.s3.util.S3Consts.X_AMZ_CONTENT_SHA256;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -61,6 +64,8 @@
import org.apache.hadoop.ozone.web.utils.OzoneUtils;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
/**
* Class to test Multipart upload where parts are created with copy header.
@@ -113,9 +118,7 @@ public static void setUp() throws Exception {
OzoneUtils.formatTime(sourceKeyLastModificationTime +
1000 * 60 * 24);
- // Make sure DELAY_MS has passed, otherwise
- // afterSourceKeyModificationTimeStr will be in the future
- // and thus invalid
+ // Make sure afterSourceKeyModificationTimeStr is in the past.
long currentTime = System.currentTimeMillis();
long sleepMs = sourceKeyLastModificationTime + DELAY_MS - currentTime;
if (sleepMs > 0) {
@@ -289,6 +292,111 @@ public String toString() {
}
}
+ @ParameterizedTest
+ @CsvSource({
+ "match, true, false", "match, false, true",
+ "none-match, true, true", "none-match, false, false"
+ })
+ public void testMultipartETagHeaders(String condition, boolean matching,
boolean rejected) throws Exception {
+ for (String range : new String[]{null, "bytes=0-3"}) {
+ String key = "etag-" + condition + "-" + matching + "-" + (range == null
? "full" : "range");
+ setHeaders();
+ String uploadID = initiateMultipartUpload(endpoint,
OzoneConsts.S3_BUCKET, key);
+ Map<String, String> headers = new HashMap<>();
+ headers.put(COPY_SOURCE_HEADER, OzoneConsts.S3_BUCKET + "/" +
EXISTING_KEY);
+ headers.put(COPY_SOURCE_IF_PREFIX + condition,
+ "\"" + (matching ? DigestUtils.md5Hex(EXISTING_KEY_CONTENT) :
"wrong-etag") + "\"");
+ if (range != null) {
+ headers.put(COPY_SOURCE_HEADER_RANGE, range);
+ }
+ setHeaders(headers);
+ if (rejected) {
+ OS3Exception ex = assertThrows(OS3Exception.class,
+ () -> put(endpoint, OzoneConsts.S3_BUCKET, key, 1, uploadID, ""));
+ assertEquals(ERROR_CODE, ex.getCode());
+ assertEquals(412, ex.getHttpCode());
+ assertEquals(0,
client.getObjectStore().getS3Bucket(OzoneConsts.S3_BUCKET)
+ .listParts(key, uploadID, 0, 100).getPartInfoList().size());
+ } else {
+ assertSucceeds(() -> put(endpoint, OzoneConsts.S3_BUCKET, key, 1,
uploadID, ""));
+ }
+ }
+ }
+
+ @ParameterizedTest
+ @CsvSource({"match, false", "none-match, true"})
+ public void testMultipartETagAndTimestampHeaders(String condition, boolean
rejected) throws Exception {
+ String key = "etag-timestamp-" + condition;
+ setHeaders();
+ String uploadID = initiateMultipartUpload(endpoint, OzoneConsts.S3_BUCKET,
key);
+ Map<String, String> headers = new HashMap<>();
+ headers.put(COPY_SOURCE_HEADER, OzoneConsts.S3_BUCKET + "/" +
EXISTING_KEY);
+ headers.put(COPY_SOURCE_IF_PREFIX + condition, "\"" +
DigestUtils.md5Hex(EXISTING_KEY_CONTENT) + "\"");
+ headers.put("match".equals(condition) ? COPY_SOURCE_IF_UNMODIFIED_SINCE :
COPY_SOURCE_IF_MODIFIED_SINCE,
+ beforeSourceKeyModificationTimeStr);
+ setHeaders(headers);
+ if (rejected) {
+ OS3Exception ex = assertThrows(OS3Exception.class,
+ () -> put(endpoint, OzoneConsts.S3_BUCKET, key, 1, uploadID, ""));
+ assertEquals(ERROR_CODE, ex.getCode());
+ assertEquals(412, ex.getHttpCode());
+ } else {
+ assertSucceeds(() -> put(endpoint, OzoneConsts.S3_BUCKET, key, 1,
uploadID, ""));
+ }
+ }
+
+ @ParameterizedTest
+ @CsvSource({
+ "match, true, false", "match, false, true",
+ "none-match, true, true", "none-match, false, false"
+ })
+ public void testMultipartETagWithFutureDate(String condition, boolean
matching, boolean rejected) throws Exception {
+ String key = "etag-future-" + condition + "-" + matching;
+ setHeaders();
+ String uploadID = initiateMultipartUpload(endpoint, OzoneConsts.S3_BUCKET,
key);
+ setHeaders(ImmutableMap.of(
+ COPY_SOURCE_HEADER, OzoneConsts.S3_BUCKET + "/" + EXISTING_KEY,
+ COPY_SOURCE_IF_PREFIX + condition,
+ "\"" + (matching ? DigestUtils.md5Hex(EXISTING_KEY_CONTENT) :
"wrong-etag") + "\"",
+ COPY_SOURCE_IF_MODIFIED_SINCE, futureTimeStr));
+ if (rejected) {
+ OS3Exception ex = assertThrows(OS3Exception.class,
+ () -> put(endpoint, OzoneConsts.S3_BUCKET, key, 1, uploadID, ""));
+ assertEquals(ERROR_CODE, ex.getCode());
+ assertEquals(412, ex.getHttpCode());
+ } else {
+ assertSucceeds(() -> put(endpoint, OzoneConsts.S3_BUCKET, key, 1,
uploadID, ""));
+ }
+ }
+
+ @Test
+ public void testMultipartCopyWithStaleETag() throws Exception {
+ setHeaders();
+ String sourceKey = "overwritten-source";
+ String key = "stale-etag-copy";
+ String uploadID = initiateMultipartUpload(endpoint, OzoneConsts.S3_BUCKET,
key);
+ OzoneBucket bucket =
client.getObjectStore().getS3Bucket(OzoneConsts.S3_BUCKET);
+ for (String content : new String[]{EXISTING_KEY_CONTENT, "updated
content"}) {
+ try (OutputStream stream = bucket.createKey(sourceKey, content.length(),
+ ReplicationConfig.fromTypeAndFactor(ReplicationType.RATIS,
ReplicationFactor.THREE),
+ ImmutableMap.of(OzoneConsts.ETAG, DigestUtils.md5Hex(content)))) {
+ stream.write(content.getBytes(UTF_8));
+ }
+ }
+ String oldETag = DigestUtils.md5Hex(EXISTING_KEY_CONTENT);
+ uploadPart(endpoint, OzoneConsts.S3_BUCKET, key, 1, uploadID,
EXISTING_KEY_CONTENT);
+ String partETag = bucket.listParts(key, uploadID, 0,
100).getPartInfoList().get(0).getETag();
+ setHeaders(ImmutableMap.of(COPY_SOURCE_HEADER, OzoneConsts.S3_BUCKET + "/"
+ sourceKey,
+ COPY_SOURCE_IF_MATCH, "\"" + oldETag + "\""));
+ OS3Exception ex = assertThrows(OS3Exception.class,
+ () -> put(endpoint, OzoneConsts.S3_BUCKET, key, 1, uploadID, ""));
+ assertEquals(ERROR_CODE, ex.getCode());
+ assertEquals(412, ex.getHttpCode());
+ OzoneMultipartUploadPartListParts parts = bucket.listParts(key, uploadID,
0, 100);
+ assertEquals(1, parts.getPartInfoList().size());
+ assertEquals(partETag, parts.getPartInfoList().get(0).getETag());
+ }
+
@Test
public void testMultipartTSHeaders() throws Exception {
for (CopyIfTimestampTestCase t : CopyIfTimestampTestCase.values()) {
diff --git
a/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/endpoint/TestObjectGet.java
b/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/endpoint/TestObjectGet.java
index 6e33f2f77af..2c9344a8ade 100644
---
a/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/endpoint/TestObjectGet.java
+++
b/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/endpoint/TestObjectGet.java
@@ -231,7 +231,7 @@ public void testGetIfModifiedSinceReturnsNotModified()
throws IOException, OS3Exception {
when(headers.getHeaderString(IF_MODIFIED_SINCE_HEADER))
.thenReturn(formatHttpDate(bucket.getKey(KEY_NAME)
- .getModificationTime().plusSeconds(60)));
+ .getModificationTime()));
Response response = get(rest, BUCKET_NAME, KEY_NAME);
assertEquals(Response.Status.NOT_MODIFIED.getStatusCode(),
diff --git
a/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/endpoint/TestS3ConditionalRequest.java
b/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/endpoint/TestS3ConditionalRequest.java
new file mode 100644
index 00000000000..1879e945852
--- /dev/null
+++
b/hadoop-ozone/s3gateway/src/test/java/org/apache/hadoop/ozone/s3/endpoint/TestS3ConditionalRequest.java
@@ -0,0 +1,92 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+package org.apache.hadoop.ozone.s3.endpoint;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.time.Instant;
+import java.util.Collections;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.Response;
+import org.apache.hadoop.ozone.client.OzoneKey;
+import
org.apache.hadoop.ozone.s3.endpoint.S3ConditionalRequest.PreconditionContext;
+import org.apache.hadoop.ozone.s3.exception.OS3Exception;
+import org.apache.hadoop.ozone.s3.util.S3Consts;
+import org.apache.hadoop.ozone.web.utils.OzoneUtils;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.EnumSource;
+
+/**
+ * Tests shared conditional request date handling.
+ */
+class TestS3ConditionalRequest {
+
+ @ParameterizedTest
+ @EnumSource(PreconditionContext.class)
+ void testFutureDatesAreIgnored(PreconditionContext context) throws Exception
{
+ Instant future = Instant.now().plusSeconds(86400);
+ HttpHeaders headers = mock(HttpHeaders.class);
+ OzoneKey key = mock(OzoneKey.class);
+ when(key.getMetadata()).thenReturn(Collections.emptyMap());
+ String modifiedHeader = context == PreconditionContext.READ
+ ? S3Consts.IF_MODIFIED_SINCE_HEADER :
S3Consts.COPY_SOURCE_IF_MODIFIED_SINCE;
+ String unmodifiedHeader = context == PreconditionContext.READ
+ ? S3Consts.IF_UNMODIFIED_SINCE_HEADER :
S3Consts.COPY_SOURCE_IF_UNMODIFIED_SINCE;
+
when(headers.getHeaderString(modifiedHeader)).thenReturn(OzoneUtils.formatTime(future.toEpochMilli()));
+ when(key.getModificationTime()).thenReturn(future.minusSeconds(172800));
+ assertNull(S3ConditionalRequest.evaluatePreconditions(headers, "key", key,
context));
+
+ when(headers.getHeaderString(modifiedHeader)).thenReturn(null);
+
when(headers.getHeaderString(unmodifiedHeader)).thenReturn(OzoneUtils.formatTime(future.toEpochMilli()));
+ when(key.getModificationTime()).thenReturn(future.plusSeconds(86400));
+ assertNull(S3ConditionalRequest.evaluatePreconditions(headers, "key", key,
context));
+ }
+
+ @ParameterizedTest
+ @CsvSource({"READ, 0", "READ, 500", "COPY_SOURCE, 0", "COPY_SOURCE, 500"})
+ void testSameSecondDateConditions(PreconditionContext context, long millis)
throws Exception {
+ Instant since = Instant.parse("2020-01-01T00:00:00Z");
+ HttpHeaders headers = mock(HttpHeaders.class);
+ OzoneKey key = mock(OzoneKey.class);
+ when(key.getMetadata()).thenReturn(Collections.emptyMap());
+ when(key.getModificationTime()).thenReturn(since.plusMillis(millis));
+ String modifiedHeader = context == PreconditionContext.READ
+ ? S3Consts.IF_MODIFIED_SINCE_HEADER :
S3Consts.COPY_SOURCE_IF_MODIFIED_SINCE;
+ String unmodifiedHeader = context == PreconditionContext.READ
+ ? S3Consts.IF_UNMODIFIED_SINCE_HEADER :
S3Consts.COPY_SOURCE_IF_UNMODIFIED_SINCE;
+
when(headers.getHeaderString(modifiedHeader)).thenReturn(OzoneUtils.formatTime(since.toEpochMilli()));
+ if (context == PreconditionContext.READ) {
+ try (Response response =
S3ConditionalRequest.evaluatePreconditions(headers, "key", key, context)) {
+ assertEquals(304, response.getStatus());
+ }
+ } else {
+ OS3Exception ex = assertThrows(OS3Exception.class,
+ () -> S3ConditionalRequest.evaluatePreconditions(headers, "key",
key, context));
+ assertEquals(412, ex.getHttpCode());
+ }
+
+ when(headers.getHeaderString(modifiedHeader)).thenReturn(null);
+
when(headers.getHeaderString(unmodifiedHeader)).thenReturn(OzoneUtils.formatTime(since.toEpochMilli()));
+ assertNull(S3ConditionalRequest.evaluatePreconditions(headers, "key", key,
context));
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]