From 107da3e75ac2cdc9b710a6e073f120ed8a0c4f5b Mon Sep 17 00:00:00 2001 From: Ben Wart Date: Thu, 22 Oct 2026 14:32:50 -0700 Subject: [PATCH] fix(s3): check CompleteMultipartUpload conditions atomically with the write (#6286) * fix(s3): check CompleteMultipartUpload conditions atomically with the write CompleteMultipartUpload judged If-Match and If-None-Match only in the controller, before any lock, and then stored the object with options that carried neither header. The recheck storeObject does under the bucket monitor for PutObject therefore never ran for a completion, so concurrent completions with If-None-Match: * on one key could all return 200, the last body winning. completeMultipartUpload now takes ifMatch and ifNoneMatch and passes them on the store options, so they are rechecked under the bucket monitor together with the write. The controller's early check stays, to spare assembling parts for a request that will fail. * test(s3): race conditional CompleteMultipartUpload over HTTP 16 barrier-synced CompleteMultipartUpload requests with If-None-Match: * on one key: exactly one 200, the rest 412, and the stored body is the winner's. Mirrors the existing concurrent PutObject test. * test(s3): share the barrier race harness between conditional-write tests The concurrent PutObject and CompleteMultipartUpload If-None-Match tests now use one raceStatusCodes helper for the barrier, executor, timeouts and shutdown, so the two cannot drift. --- .../floci/services/s3/S3Controller.java | 2 +- .../floci/services/s3/S3Service.java | 16 ++- .../s3/S3ConditionalWriteIntegrationTest.java | 94 +++++++++---- .../S3MultipartConditionalCompleteTest.java | 129 ++++++++++++++++++ 4 files changed, 211 insertions(+), 30 deletions(-) create mode 100644 src/test/java/io/github/hectorvent/floci/services/s3/S3MultipartConditionalCompleteTest.java diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java index ef5a1dcecb..7768b79177 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java @@ -1697,7 +1697,7 @@ public class S3Controller { S3Checksum expectedChecksum = extractChecksum(httpHeaders); S3Object obj = s3Service.completeMultipartUpload(bucket, key, uploadId, partNumbers, completedPartETags(completedParts), completedPartChecksums(completedParts), checksumType, - expectedChecksum, multipartObjectSize(httpHeaders, uriInfo)); + expectedChecksum, multipartObjectSize(httpHeaders, uriInfo), ifMatch, ifNoneMatch); String baseUrl = uriInfo.getBaseUri().toString(); if (baseUrl.endsWith("/")) { baseUrl = baseUrl.substring(0, baseUrl.length() - 1); diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java index c91a16c06d..ac722394e9 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java @@ -4695,6 +4695,18 @@ public class S3Service implements Resettable, ResourceProvider { public S3Object completeMultipartUpload(String bucket, String key, String uploadId, List partNumbers, Map partETags, Map partChecksums, String checksumType, S3Checksum expectedChecksum, Long expectedObjectSize) { + return completeMultipartUpload(bucket, key, uploadId, partNumbers, partETags, partChecksums, + checksumType, expectedChecksum, expectedObjectSize, null, null); + } + + /** + * {@code ifMatch} and {@code ifNoneMatch} are judged by storeObject under the bucket's monitor, + * together with the write, so concurrent conditional completions on one key cannot all succeed. + */ + public S3Object completeMultipartUpload(String bucket, String key, String uploadId, List partNumbers, + Map partETags, Map partChecksums, + String checksumType, S3Checksum expectedChecksum, Long expectedObjectSize, + String ifMatch, String ifNoneMatch) { S3Object completed = withMultipartOperationLock(bucket, uploadId, () -> { MultipartUpload upload = getMultipartUpload(bucket, key, uploadId); @@ -4788,7 +4800,9 @@ public class S3Service implements Resettable, ResourceProvider { .withObjectLockMode(upload.getObjectLockMode()) .withRetainUntilDate(upload.getRetainUntilDate()) .withLegalHoldStatus(upload.getLegalHoldStatus()) - .withTagging(upload.getTagging()), + .withTagging(upload.getTagging()) + .withIfMatch(ifMatch) + .withIfNoneMatch(ifNoneMatch), compositeETag, upload.getInitiatorAccountId() != null ? upload.getInitiatorAccountId() : ownerId()); } finally { diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3ConditionalWriteIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3ConditionalWriteIntegrationTest.java index 785f92bef7..36adbcb175 100644 --- a/src/test/java/io/github/hectorvent/floci/services/s3/S3ConditionalWriteIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3ConditionalWriteIntegrationTest.java @@ -12,11 +12,11 @@ import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; +import java.util.function.IntFunction; import static io.restassured.RestAssured.given; import static java.util.Collections.frequency; import static java.util.concurrent.TimeUnit.SECONDS; -import static java.util.stream.Collectors.toList; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.notNullValue; @@ -67,35 +67,18 @@ class S3ConditionalWriteIntegrationTest { String bucket = createBucket("put-if-none-concurrent"); String key = "object.txt"; int writers = 16; - CyclicBarrier barrier = new CyclicBarrier(writers); - ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor(); - try { - List> futures = java.util.stream.IntStream.range(0, writers) - .mapToObj(writer -> executor.submit(() -> { - barrier.await(); - return given() - .header("If-None-Match", "*") - .body("writer-" + writer) - .when() - .put("/" + bucket + "/" + key) - .then() - .extract() - .statusCode(); - })) - .collect(toList()); + List statusCodes = raceStatusCodes(writers, writer -> given() + .header("If-None-Match", "*") + .body("writer-" + writer) + .when() + .put("/" + bucket + "/" + key) + .then() + .extract() + .statusCode()); - List statusCodes = new ArrayList<>(); - for (Future future : futures) { - statusCodes.add(future.get(30, SECONDS)); - } - - assertEquals(1, frequency(statusCodes, 200)); - assertEquals(writers - 1, frequency(statusCodes, 412)); - } - finally { - executor.shutdownNow(); - } + assertEquals(1, frequency(statusCodes, 200)); + assertEquals(writers - 1, frequency(statusCodes, 412)); } @Test @@ -249,6 +232,34 @@ class S3ConditionalWriteIntegrationTest { assertObjectBody(bucket, "object.txt", "first"); } + @Test + void concurrentCompleteMultipartUpload_ifNoneMatchStar_allowsOnlyOneWriter() throws Exception { + String bucket = createBucket("mpu-if-none-concurrent"); + String key = "object.txt"; + int writers = 16; + List uploadIds = new ArrayList<>(); + List partETags = new ArrayList<>(); + for (int writer = 0; writer < writers; writer++) { + String uploadId = initiateMultipartUpload(bucket, key); + uploadIds.add(uploadId); + partETags.add(uploadPart(bucket, key, uploadId, 1, "writer-" + writer)); + } + + List statusCodes = raceStatusCodes(writers, writer -> given() + .contentType("application/xml") + .header("If-None-Match", "*") + .body(completeMultipartXml(1, partETags.get(writer))) + .when() + .post("/" + bucket + "/" + key + "?uploadId=" + uploadIds.get(writer)) + .then() + .extract() + .statusCode()); + + assertEquals(1, frequency(statusCodes, 200)); + assertEquals(writers - 1, frequency(statusCodes, 412)); + assertObjectBody(bucket, key, "writer-" + statusCodes.indexOf(200)); + } + @Test void completeMultipartUpload_ifMatch_succeedsOnMatch() { String bucket = createBucket("mpu-if-match"); @@ -539,6 +550,33 @@ class S3ConditionalWriteIntegrationTest { .body("Error.Code", equalTo("NotImplemented")); } + /** + * Releases {@code writers} requests at once behind a barrier and returns each one's status + * code, in writer order. + */ + private static List raceStatusCodes(int writers, IntFunction request) throws Exception { + CyclicBarrier barrier = new CyclicBarrier(writers); + ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor(); + try { + List> futures = new ArrayList<>(); + for (int writer = 0; writer < writers; writer++) { + int current = writer; + futures.add(executor.submit(() -> { + barrier.await(); + return request.apply(current); + })); + } + List statusCodes = new ArrayList<>(); + for (Future future : futures) { + statusCodes.add(future.get(30, SECONDS)); + } + return statusCodes; + } + finally { + executor.shutdownNow(); + } + } + private static void assertPreconditionFailed(ValidatableResponse response, String condition) { response.statusCode(412) .body("Error.Code", equalTo("PreconditionFailed")) diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3MultipartConditionalCompleteTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3MultipartConditionalCompleteTest.java new file mode 100644 index 0000000000..499e4ff3a1 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3MultipartConditionalCompleteTest.java @@ -0,0 +1,129 @@ +package io.github.hectorvent.floci.services.s3; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.services.s3.model.S3Object; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * CompleteMultipartUpload's If-Match / If-None-Match must be judged atomically with the write, as + * PutObject's are, so concurrent conditional completions on one key cannot all succeed. + */ +class S3MultipartConditionalCompleteTest { + + private static final String BUCKET = "conditional-complete"; + private static final String KEY = "object"; + + @TempDir + Path tempDir; + + private S3Service newService(boolean inMemory) { + S3Service service = new S3Service(new InMemoryStorage<>(), new InMemoryStorage<>(), + tempDir.resolve(inMemory ? "memory" : "disk"), inMemory); + service.createBucket(BUCKET, "us-east-1"); + return service; + } + + private static String uploadOnePart(S3Service service, byte[] data) { + String uploadId = service.initiateMultipartUpload(BUCKET, KEY, "application/octet-stream").getUploadId(); + service.uploadPart(BUCKET, KEY, uploadId, 1, data); + return uploadId; + } + + private static S3Object complete(S3Service service, String uploadId, String ifMatch, String ifNoneMatch) { + return service.completeMultipartUpload(BUCKET, KEY, uploadId, List.of(1), Map.of(), Map.of(), + null, null, null, ifMatch, ifNoneMatch); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void ifNoneMatchStarFailsWhenTheKeyExistsAndKeepsTheObjectAndUpload(boolean inMemory) { + S3Service service = newService(inMemory); + byte[] original = "original".getBytes(StandardCharsets.UTF_8); + service.putObject(BUCKET, KEY, original, "application/octet-stream", Map.of()); + String uploadId = uploadOnePart(service, "replacement".getBytes(StandardCharsets.UTF_8)); + + AwsException failed = assertThrows(AwsException.class, () -> complete(service, uploadId, null, "*")); + + assertEquals(412, failed.getHttpStatus()); + assertEquals("PreconditionFailed", failed.getErrorCode()); + assertArrayEquals(original, service.getObject(BUCKET, KEY).getData()); + assertEquals(uploadId, service.getMultipartUpload(BUCKET, KEY, uploadId).getUploadId()); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void ifMatchFailsWhenTheETagDiffers(boolean inMemory) { + S3Service service = newService(inMemory); + service.putObject(BUCKET, KEY, "original".getBytes(StandardCharsets.UTF_8), + "application/octet-stream", Map.of()); + String uploadId = uploadOnePart(service, "replacement".getBytes(StandardCharsets.UTF_8)); + + AwsException failed = assertThrows(AwsException.class, + () -> complete(service, uploadId, "\"0123456789abcdef0123456789abcdef\"", null)); + + assertEquals(412, failed.getHttpStatus()); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void concurrentIfNoneMatchStarCompletionsHaveExactlyOneWinner(boolean inMemory) throws Exception { + S3Service service = newService(inMemory); + int writers = 16; + List uploadIds = new ArrayList<>(); + for (int i = 0; i < writers; i++) { + uploadIds.add(uploadOnePart(service, ("writer-" + i).getBytes(StandardCharsets.UTF_8))); + } + + CyclicBarrier start = new CyclicBarrier(writers); + ExecutorService pool = Executors.newFixedThreadPool(writers); + List> results = new ArrayList<>(); + try { + for (int i = 0; i < writers; i++) { + String uploadId = uploadIds.get(i); + byte[] body = ("writer-" + i).getBytes(StandardCharsets.UTF_8); + results.add(pool.submit(() -> { + start.await(5, TimeUnit.SECONDS); + try { + complete(service, uploadId, null, "*"); + return body; + } catch (AwsException e) { + assertEquals(412, e.getHttpStatus()); + return null; + } + })); + } + List winners = new ArrayList<>(); + for (Future result : results) { + byte[] won = result.get(10, TimeUnit.SECONDS); + if (won != null) { + winners.add(won); + } + } + + assertEquals(1, winners.size(), "exactly one conditional completion may create the key"); + assertArrayEquals(winners.get(0), service.getObject(BUCKET, KEY).getData()); + } finally { + pool.shutdownNow(); + assertTrue(pool.awaitTermination(5, TimeUnit.SECONDS)); + } + } +}