Light, fluffy, and always free - The AWS Local Emulator alternative
fix(s3): make versionId=null name only the null version (#5887)
Priamo Germosen63cf09a39691
diff --git a/docs/services/s3.md b/docs/services/s3.mdindex 84b069bd83..21e44fe27c 100644--- a/docs/services/s3.md+++ b/docs/services/s3.md@@ -81,12 +81,24 @@ specific object version through the four `?annotation` operations. Notes on theLock-protected versions, annotation put and delete follow the same rules as object delete:governance retention requires `x-amz-bypass-governance-retention` (put never takes the bypass),compliance and legal hold always block.-- The literal `versionId=null` (as reported by ListObjectVersions for pre-versioning objects)- addresses the pre-versioning entry.+- The literal `versionId=null` names the null version only, as it does on every object operation+ (see [Object Versions](#object-versions)); a key without one answers `NoSuchKey`, as for any+ missing version.- Annotations are stored per AWS account. With `globalBucketNamespace` enabled, object readsresolve cross-account but annotation reads, writes, and listings stay in the caller's account.- S3 Metadata annotation tables and annotation replication are not implemented.+## Object Versions++A request that names `versionId=null`, the id ListObjectVersions reports for an object written+while versioning was off or suspended, acts on that null version only: GetObject, HeadObject,+GetObjectAttributes, the object ACL, tagging, retention, legal hold, annotations and a copy source.+A key whose current version was written with versioning on has no null version, so such a request+answers as for any missing version: `404 NoSuchVersion`, or `404 NoSuchKey` for the annotation+operations. S3 keeps a null version that a later+versioned write replaces as a noncurrent version; Floci does not keep it, so after such a write the+key has no null version.+## Lifecycle ExpirationA bucket's lifecycle configuration is stored as sent and its expiration actions are applied by adiff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.javaindex 877a2ddddb..427d0df13d 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@@ -1597,8 +1597,8 @@ public class S3Service implements Resettable, ResourceProvider {if (ownershipIsEnforced(bucket)) {return false;}- String storeKey = versionId != null ? versionedKey(bucketName, key, versionId) : objectKey(bucketName, key);- return objectStore.get(storeKey)+ return objectStore.get(versionStoreKey(bucketName, key, versionId))+ .filter(object -> isNamedVersion(object, versionId)).filter(object -> !object.isDeleteMarker()).map(S3Object::getAcl).map(S3AclPublicAccessEvaluator::aclAllowsPublicRead)@@ -1661,16 +1661,7 @@ public class S3Service implements Resettable, ResourceProvider {}public S3Object getObject(String bucketName, String key, String versionId) {- if ("null".equals(versionId)) {- String bucketOwnerAccount = resolveBucketEntry(bucketName)- .orElseThrow(() -> new AwsException("NoSuchBucket",- "The specified bucket does not exist.", 404))- .account();- S3Object obj = getObjectMetadata(bucketName, key, versionId);- obj.setData(readFile(bucketOwnerAccount, bucketName, key));- return obj;- }- if (versionId != null) {+ if (versionId != null && !"null".equals(versionId)) {// An explicit version's file is immutable once written (see storeObjectInternal) and// never reused by a later PUT, so this pairing can never race a concurrent overwrite.String bucketOwnerAccount = resolveBucketEntry(bucketName)@@ -1681,7 +1672,7 @@ public class S3Service implements Resettable, ResourceProvider {obj.setData(readVersionedFile(bucketOwnerAccount, bucketName, key, versionId));return obj;}- return getLatestObject(bucketName, key);+ return getLatestObject(bucketName, key, versionId);}/**@@ -1703,8 +1694,8 @@ public class S3Service implements Resettable, ResourceProvider {* since nothing can concurrently overwrite a key without immediately stamping one, a null* token is only ever observed when untouched, and untouched means nothing to race against.*/- private S3Object getLatestObject(String bucketName, String key) {- Snapshot<byte[]> snapshot = readLatestSnapshot(bucketName, key,+ private S3Object getLatestObject(String bucketName, String key, String versionId) {+ Snapshot<byte[]> snapshot = readLatestSnapshot(bucketName, key, versionId,account -> readFile(account, bucketName, key), data -> { });snapshot.object().setData(snapshot.body());return snapshot.object();@@ -1714,9 +1705,12 @@ public class S3Service implements Resettable, ResourceProvider {/*** The optimistic read described on {@link #getLatestObject}, for any body type: {@code readBody}- * gets the bucket owner's account and {@code discard} releases a body read during a race.+ * gets the bucket owner's account and {@code discard} releases a body read during a race. It reads+ * the object at the plain key, which is the current version when {@code versionId} is null and+ * must be the null version when it is {@code "null"}: a write landing mid-read retries the read,+ * which then finds the null version gone.*/- private <B> Snapshot<B> readLatestSnapshot(String bucketName, String key,+ private <B> Snapshot<B> readLatestSnapshot(String bucketName, String key, String versionId,Function<String, B> readBody, Consumer<B> discard) {AccountAwareStorageBackend.OwnedEntry<Bucket> ownedBucket = resolveBucketEntry(bucketName).orElseThrow(() -> new AwsException("NoSuchBucket",@@ -1728,7 +1722,7 @@ public class S3Service implements Resettable, ResourceProvider {// (the recheck disagreeing with getObjectMetadata about where this key lives) fails loudly// with a clear error instead of spinning forever re-reading the file and exhausting the heap.for (int attempt = 0; attempt < 10_000; attempt++) {- S3Object obj = getObjectMetadata(bucketName, key, null);+ S3Object obj = getObjectMetadata(bucketName, key, versionId);B body = readBody.apply(bucketOwnerAccount);synchronized (bucket) {S3Object current = resolveObjectForAccount(bucketOwnerAccount, storeKey).orElse(null);@@ -1765,8 +1759,8 @@ public class S3Service implements Resettable, ResourceProvider {S3Object obj = getObject(bucketName, key, versionId);return new ObjectRead(obj, new ByteArrayInputStream(obj.getData()));}- if (versionId == null) {- Snapshot<FileChannel> snapshot = readLatestSnapshot(bucketName, key,+ if (versionId == null || "null".equals(versionId)) {+ Snapshot<FileChannel> snapshot = readLatestSnapshot(bucketName, key, versionId,account -> openForRead(resolveObjectPathForRead(account, bucketName, key)),S3Service::closeQuietly);return objectRead(snapshot.object(), snapshot.body());@@ -1776,10 +1770,8 @@ public class S3Service implements Resettable, ResourceProvider {"The specified bucket does not exist.", 404)).account();S3Object obj = getObjectMetadata(bucketName, key, versionId);- Path path = "null".equals(versionId)- ? resolveObjectPathForRead(bucketOwnerAccount, bucketName, key)- : resolveVersionedPathForRead(bucketOwnerAccount, bucketName, key, versionId);- return objectRead(obj, openForRead(path));+ return objectRead(obj, openForRead(+ resolveVersionedPathForRead(bucketOwnerAccount, bucketName, key, versionId)));}private static ObjectRead objectRead(S3Object obj, FileChannel channel) {@@ -1866,7 +1858,7 @@ public class S3Service implements Resettable, ResourceProvider {}public S3Object getObjectMetadata(String bucketName, String key, String versionId) {- return copyObject(getStoredObject(bucketName, key, "null".equals(versionId) ? null : versionId));+ return copyObject(getStoredObject(bucketName, key, versionId));}public GetObjectAttributesResult getObjectAttributes(String bucketName, String key, String versionId,@@ -1901,14 +1893,19 @@ public class S3Service implements Resettable, ResourceProvider {return getStoredObjectEntry(bucketName, key, versionId).value();}+ /**+ * The version {@code versionId} names, or the current version when it is null. The literal+ * {@code "null"} names the null version only (see {@link #isNamedVersion}), and a key without one+ * answers as any missing version does.+ */private AccountAwareStorageBackend.OwnedEntry<S3Object> getStoredObjectEntry(String bucketName, String key, String versionId) {AccountAwareStorageBackend.OwnedEntry<Bucket> ownedBucket = resolveBucketEntry(bucketName).orElseThrow(() -> new AwsException("NoSuchBucket","The specified bucket does not exist.", 404));- String storeKey = versionId != null ? versionedKey(bucketName, key, versionId) : objectKey(bucketName, key);- S3Object object = resolveObjectForAccount(ownedBucket.account(), storeKey)+ S3Object object = resolveObjectForAccount(ownedBucket.account(), versionStoreKey(bucketName, key, versionId))+ .filter(existing -> isNamedVersion(existing, versionId)).orElseThrow(() -> versionId != null? new AwsException("NoSuchVersion", "The specified version does not exist.", 404): new AwsException("NoSuchKey", "The specified key does not exist.", 404));@@ -1918,6 +1915,27 @@ public class S3Service implements Resettable, ResourceProvider {return new AccountAwareStorageBackend.OwnedEntry<>(ownedBucket.account(), object);}+ /**+ * Where the version {@code versionId} names is stored: the current version (null) and the null+ * version ({@code "null"}) at the plain object key, where floci keeps the null version until a+ * versioned write replaces it, and any other version at its versioned key.+ */+ private String versionStoreKey(String bucketName, String key, String versionId) {+ return versionId == null || "null".equals(versionId)+ ? objectKey(bucketName, key)+ : versionedKey(bucketName, key, versionId);+ }++ /**+ * Whether {@code object}, found at {@link #versionStoreKey}, is the version {@code versionId}+ * names. The literal {@code "null"} names only the null version, an object without a version id:+ * a current version that has one is not it, and floci keeps no null version beside one, so such+ * a request names a version that does not exist.+ */+ private static boolean isNamedVersion(S3Object object, String versionId) {+ return !"null".equals(versionId) || object.getVersionId() == null;+ }+// AWS lists part-level checksums only for composite objects; a full-object multipart object// reports its part count alone.private GetObjectAttributesParts buildObjectParts(S3Object object, Integer maxParts, Integer partNumberMarker) {@@ -2158,19 +2176,9 @@ public class S3Service implements Resettable, ResourceProvider {*/public boolean isGovernanceRetentionActive(String bucketName, String key, String versionId) {ensureBucketExists(bucketName);- S3Object object;- if ("null".equals(versionId)) {- // Resolved as deleteObjectLocked resolves it: the null version is the unversioned object- // at the plain key, so a versioned key named "null" would miss a retained one.- object = objectStore.get(objectKey(bucketName, key))- .filter(existing -> existing.getVersionId() == null)- .orElse(null);- } else {- object = (versionId != null- ? objectStore.get(versionedKey(bucketName, key, versionId))- : objectStore.get(objectKey(bucketName, key)))- .orElse(null);- }+ S3Object object = objectStore.get(versionStoreKey(bucketName, key, versionId))+ .filter(existing -> isNamedVersion(existing, versionId))+ .orElse(null);return object != null&& !object.isDeleteMarker()&& "GOVERNANCE".equals(object.getObjectLockMode())@@ -2449,8 +2457,8 @@ public class S3Service implements Resettable, ResourceProvider {if (inMemory) {return new CopySource(getObject(bucketName, key, versionId), null);}- if (versionId == null) {- Snapshot<Path> snapshot = readLatestSnapshot(bucketName, key,+ if (versionId == null || "null".equals(versionId)) {+ Snapshot<Path> snapshot = readLatestSnapshot(bucketName, key, versionId,account -> pinFile(resolveObjectPathForRead(account, bucketName, key)),pinned -> deleteQuietly(pinned, "pinned copy source of a read that raced an overwrite"));return checkedCopySource(snapshot.object(), snapshot.body());@@ -2460,10 +2468,8 @@ public class S3Service implements Resettable, ResourceProvider {"The specified bucket does not exist.", 404)).account();S3Object obj = getObjectMetadata(bucketName, key, versionId);- Path path = "null".equals(versionId)- ? resolveObjectPathForRead(bucketOwnerAccount, bucketName, key)- : resolveVersionedPathForRead(bucketOwnerAccount, bucketName, key, versionId);- return checkedCopySource(obj, pinFile(path));+ return checkedCopySource(obj, pinFile(+ resolveVersionedPathForRead(bucketOwnerAccount, bucketName, key, versionId)));}private CopySource checkedCopySource(S3Object obj, Path pinned) {@@ -2862,13 +2868,13 @@ public class S3Service implements Resettable, ResourceProvider {}/**- * Tags of one version, or of the current version when {@code versionId} is null or "null". The- * IAM condition context reads {@code s3:ExistingObjectTag} here, so these must be the tags of the- * object a request reaches, and GetObject, HeadObject and the annotation operations still serve- * the current version for "null". GetObjectTagging reads {@link #getObjectTaggingResult}.+ * Tags of one version, or of the current version when {@code versionId} is null; "null" names the+ * null version only. The IAM condition context reads {@code s3:ExistingObjectTag} here, so these+ * must be the tags of the version a request reaches. GetObjectTagging reads+ * {@link #getObjectTaggingResult}.*/public Map<String, String> getObjectTagging(String bucketName, String key, String versionId) {- S3Object obj = getStoredObject(bucketName, key, "null".equals(versionId) ? null : versionId);+ S3Object obj = getStoredObject(bucketName, key, versionId);return obj.getTags() != null ? obj.getTags() : Map.of();}@@ -2917,10 +2923,8 @@ public class S3Service implements Resettable, ResourceProvider {/*** The version a tagging request acts on: the one {@code versionId} names, or the current version- * when it is null. The literal {@code "null"} names the null version, resolved as- * deleteObjectLocked resolves it: the object at the plain key, when that object has no version- * id. A current version with an id is not it, and floci keeps no null version beside one, so the- * request names a version that does not exist. A delete marker, named or current, has no tags:+ * when it is null, with "null" naming the null version only (see {@link #isNamedVersion}). A+ * delete marker, named or current, has no tags:* S3 refuses the request with MethodNotAllowed, naming the method and the marker.*/private AccountAwareStorageBackend.OwnedEntry<S3Object> getTaggingTargetEntry(@@ -2928,12 +2932,8 @@ public class S3Service implements Resettable, ResourceProvider {AccountAwareStorageBackend.OwnedEntry<Bucket> ownedBucket = resolveBucketEntry(bucketName).orElseThrow(() -> new AwsException("NoSuchBucket","The specified bucket does not exist.", 404));- boolean nullVersion = "null".equals(versionId);- String storeKey = versionId == null || nullVersion- ? objectKey(bucketName, key)- : versionedKey(bucketName, key, versionId);- S3Object object = resolveObjectForAccount(ownedBucket.account(), storeKey)- .filter(existing -> !nullVersion || existing.getVersionId() == null)+ S3Object object = resolveObjectForAccount(ownedBucket.account(), versionStoreKey(bucketName, key, versionId))+ .filter(existing -> isNamedVersion(existing, versionId)).orElseThrow(() -> versionId != null? new AwsException("NoSuchVersion", "The specified version does not exist.", 404): new AwsException("NoSuchKey", "The specified key does not exist.", 404));@@ -2970,8 +2970,8 @@ public class S3Service implements Resettable, ResourceProvider {ObjectAnnotation annotation;String sequencer;synchronized (bucket) {- versionId = normalizeNullVersionId(versionId);S3Object parent = resolveParentObject(bucketName, key, versionId);+ versionId = normalizeNullVersionId(versionId);// Symmetric with deleteObjectAnnotation: an annotation put must not add or replace// an annotation on a retention-protected version, or the delete path's protection// is circumvented by a re-put.@@ -3024,8 +3024,8 @@ public class S3Service implements Resettable, ResourceProvider {String versionId) {Bucket bucket = requireBucket(bucketName);synchronized (bucket) {- versionId = normalizeNullVersionId(versionId);S3Object parent = resolveParentObject(bucketName, key, versionId);+ versionId = normalizeNullVersionId(versionId);validateAnnotationName(annotationName);String storeKey = annotationStoreKey(parentStoreKey(bucketName, key, versionId, parent), annotationName);return annotationStore.get(storeKey)@@ -3049,8 +3049,8 @@ public class S3Service implements Resettable, ResourceProvider {String continuationToken, String versionId) {Bucket bucket = requireBucket(bucketName);synchronized (bucket) {- versionId = normalizeNullVersionId(versionId);S3Object parent = resolveParentObject(bucketName, key, versionId);+ versionId = normalizeNullVersionId(versionId);int limit = maxAnnotationResults != null ? maxAnnotationResults : MAX_ANNOTATION_RESULTS;if (limit < 1 || limit > MAX_ANNOTATION_RESULTS) {throw new AwsException("InvalidArgument",@@ -3085,8 +3085,8 @@ public class S3Service implements Resettable, ResourceProvider {String parentVersionId;String sequencer;synchronized (bucket) {- versionId = normalizeNullVersionId(versionId);S3Object parent = resolveParentObject(bucketName, key, versionId);+ versionId = normalizeNullVersionId(versionId);// Deleting an annotation on a locked version follows DeleteObject's rules: governance// retention needs x-amz-bypass-governance-retention, compliance and legal hold always block.checkLockProtection(parent, bypassGovernance);@@ -3117,9 +3117,9 @@ public class S3Service implements Resettable, ResourceProvider {}/**- * ListObjectVersions reports pre-versioning objects with the literal VersionId {@code "null"};- * a version-echoing client sends it back. Treat it as a request for the pre-versioning entry- * at the plain object key.+ * ListObjectVersions reports the null version with the literal VersionId {@code "null"}, and a+ * version-echoing client sends it back. Once {@link #resolveParentObject} has found that version,+ * its annotations are those of the entry at the plain object key.*/private static String normalizeNullVersionId(String versionId) {return "null".equals(versionId) ? null : versionId;@@ -3181,11 +3181,13 @@ public class S3Service implements Resettable, ResourceProvider {return versionId != null ? encodedKey + "#v#" + versionId : encodedKey;}- /** Resolves the object a subresource request targets; a delete-marker latest reads as absent. */+ /**+ * Resolves the object a subresource request targets, "null" naming the null version only (see+ * {@link #isNamedVersion}); a delete-marker latest reads as absent.+ */private S3Object resolveParentObject(String bucketName, String key, String versionId) {- S3Object object = resolveObject(versionId != null- ? versionedKey(bucketName, key, versionId)- : objectKey(bucketName, key))+ S3Object object = resolveObject(versionStoreKey(bucketName, key, versionId))+ .filter(existing -> isNamedVersion(existing, versionId)).orElseThrow(() -> new AwsException("NoSuchKey","The specified key does not exist.", 404));if (object.isDeleteMarker()) {diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/S3ObjectTagConditionEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/S3ObjectTagConditionEnforcementIntegrationTest.javaindex 02539d2ed3..4112e00515 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/S3ObjectTagConditionEnforcementIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/S3ObjectTagConditionEnforcementIntegrationTest.java@@ -150,18 +150,20 @@ class S3ObjectTagConditionEnforcementIntegrationTest {}@Test- void aReadNamingTheNullVersionIsAuthorizedAgainstTheVersionItServes() {+ void aReadNamingTheNullVersionIsAuthorizedAgainstThatVersion() {Fixture f = new Fixture("nullversion", true);- // Written with versioning on, the key has no null version. S3 answers a read naming one with- // NoSuchVersion, but floci serves it the current version, so that version's tags must decide- // or the deny on them would be skipped.+ // Seeded before versioning was enabled, a/tagged-a and a/tagged-b are null versions, and a+ // read naming one is checked against its tags. a/secret, written with versioning on, has no+ // null version: a read naming one is answered NoSuchVersion and serves nothing.f.seedVersion("a/secret", "env=b");f.policy(allow("\"s3:GetObject\",\"s3:GetObjectVersion\"", f.objects(), null) + ","+ "{\"Effect\":\"Deny\",\"Action\":[\"s3:GetObject\",\"s3:GetObjectVersion\"],"+ "\"Resource\":\"" + f.objects() + "\","+ "\"Condition\":{\"StringEquals\":{\"s3:ExistingObjectTag/env\":\"b\"}}}");+ assertEquals(403, f.getVersion("a/tagged-b", "null"), "the null version carries the denied tag");+ assertEquals(200, f.getVersion("a/tagged-a", "null"), "the null version carries an allowed tag");assertEquals(403, f.get("a/secret"), "the current version carries the denied tag");- assertEquals(403, f.getVersion("a/secret", "null"), "the same version, reached through versionId=null");+ assertEquals(404, f.getVersion("a/secret", "null"), "a key without a null version serves none");}private static String allow(String actions, String resource, String condition) {diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3AuthEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3AuthEnforcementIntegrationTest.javaindex 2da195cc80..8fe1a4be6c 100644--- a/src/test/java/io/github/hectorvent/floci/services/s3/S3AuthEnforcementIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3AuthEnforcementIntegrationTest.java@@ -2464,6 +2464,33 @@ class S3AuthEnforcementIntegrationTest {given().when().get("/" + bucket + "?list-type=2").then().statusCode(200);}+ @Test+ @Order(59)+ void anAnonymousReadNamingTheNullVersionIsCheckedAgainstThatVersionsAcl() {+ String bucket = "auth-null-version-acl-bucket";+ given().filter(LOCAL_SIGNER).when().put("/" + bucket).then().statusCode(200);+ enableLegacyAcls(bucket);+ given().filter(LOCAL_SIGNER).body("old").when().put("/" + bucket + "/old").then().statusCode(200);+ given().filter(LOCAL_SIGNER)+ .body("<VersioningConfiguration><Status>Enabled</Status></VersioningConfiguration>")+ .when().put("/" + bucket + "?versioning")+ .then().statusCode(200);+ given().filter(LOCAL_SIGNER).header("x-amz-acl", "public-read").body("new")+ .when().put("/" + bucket + "/new")+ .then().statusCode(200);++ // "old", written before versioning, is the null version, and its own ACL makes it public.+ given().filter(LOCAL_SIGNER).queryParam("versionId", "null").header("x-amz-acl", "public-read")+ .when().put("/" + bucket + "/old?acl")+ .then().statusCode(200);+ given().queryParam("versionId", "null").when().get("/" + bucket + "/old")+ .then().statusCode(200).body(equalTo("old"));++ // "new" has no null version: its public current version does not make one readable.+ given().when().get("/" + bucket + "/new").then().statusCode(200).body(equalTo("new"));+ given().queryParam("versionId", "null").when().get("/" + bucket + "/new").then().statusCode(403);+ }+private static String publicObjectActionPolicy(String bucket, String action) {return publicObjectActionPolicy(bucket, "*", action);}diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3NullVersionDiskTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3NullVersionDiskTest.javanew file mode 100644index 0000000000..eaa6c332c3--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3NullVersionDiskTest.java@@ -0,0 +1,67 @@+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.CopyObjectOptions;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.function.Executable;+import org.junit.jupiter.api.io.TempDir;++import java.io.IOException;+import java.nio.charset.StandardCharsets;+import java.nio.file.Path;+import java.util.List;+import java.util.Map;++import static org.junit.jupiter.api.Assertions.assertArrayEquals;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertThrows;++/**+ * A request naming {@code versionId=null} in disk-storage mode, where the null version's bytes are+ * the object file at the plain key: GetObject streams it and CopyObject pins it, and a key without+ * a null version has neither.+ */+class S3NullVersionDiskTest {++ @TempDir+ Path tempDir;++ private S3Service s3Service;++ @BeforeEach+ void setUp() {+ s3Service = new S3Service(new InMemoryStorage<>(), new InMemoryStorage<>(), tempDir.resolve("s3"), false);+ s3Service.createBucket("bucket", "us-east-1");+ s3Service.putObject("bucket", "old.txt", bytes("null version"), "text/plain", Map.of());+ s3Service.putBucketVersioning("bucket", "Enabled");+ s3Service.putObject("bucket", "new.txt", bytes("current version"), "text/plain", Map.of());+ }++ @Test+ void theNullVersionIsStreamedAndCopiedFromTheObjectFile() throws IOException {+ try (S3Service.ObjectRead read = s3Service.openObject("bucket", "old.txt", "null")) {+ assertArrayEquals(bytes("null version"), read.body().readAllBytes());+ }++ s3Service.copyObject("bucket", "old.txt", "bucket", "copy.txt", "null", new CopyObjectOptions());++ assertArrayEquals(bytes("null version"), s3Service.getObject("bucket", "copy.txt").getData());+ }++ @Test+ void aKeyWithoutANullVersionIsNeitherStreamedNorCopied() {+ for (Executable request : List.<Executable>of(+ () -> s3Service.openObject("bucket", "new.txt", "null").close(),+ () -> s3Service.copyObject("bucket", "new.txt", "bucket", "copy.txt", "null",+ new CopyObjectOptions()))) {+ AwsException e = assertThrows(AwsException.class, request);+ assertEquals("NoSuchVersion", e.getErrorCode());+ }+ }++ private static byte[] bytes(String text) {+ return text.getBytes(StandardCharsets.UTF_8);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3VersioningIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3VersioningIntegrationTest.javaindex 1381ae6fe6..9fd4a15e05 100644--- a/src/test/java/io/github/hectorvent/floci/services/s3/S3VersioningIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3VersioningIntegrationTest.java@@ -583,6 +583,95 @@ class S3VersioningIntegrationTest {}}+ @Test+ @Order(24)+ void versionIdNullNamesOnlyTheNullVersionOnEveryObjectOperation() {+ String bucket = "versioned-null-version-test";+ given().when().put("/" + bucket).then().statusCode(200);+ // ACLs enabled, so the ACL requests below reach the version they name.+ given().body("<OwnershipControls><Rule><ObjectOwnership>ObjectWriter</ObjectOwnership></Rule></OwnershipControls>")+ .when().put("/" + bucket + "?ownershipControls").then().statusCode(200);+ given().body("old").when().put("/" + bucket + "/old").then().statusCode(200);+ given().body("<VersioningConfiguration><Status>Enabled</Status></VersioningConfiguration>")+ .when().put("/" + bucket + "?versioning").then().statusCode(200);+ given().body("new").when().put("/" + bucket + "/new").then().statusCode(200);++ // "old", written before versioning, is the null version.+ String old = "/" + bucket + "/old";+ given().queryParam("versionId", "null").when().get(old).then().statusCode(200).body(equalTo("old"));+ given().queryParam("versionId", "null").when().head(old).then().statusCode(200);+ given().queryParam("versionId", "null").header("x-amz-object-attributes", "ObjectSize")+ .when().get(old + "?attributes").then().statusCode(200)+ .body(containsString("<ObjectSize>3</ObjectSize>"));+ given().queryParam("versionId", "null").when().get(old + "?acl").then().statusCode(200);+ given().queryParam("versionId", "null").header("x-amz-acl", "private")+ .when().put(old + "?acl").then().statusCode(200);+ given().queryParam("versionId", "null").queryParam("annotationName", "labels").body("x")+ .when().put(old + "?annotation").then().statusCode(200);+ given().queryParam("versionId", "null").queryParam("annotationName", "labels")+ .when().get(old + "?annotation").then().statusCode(200);+ given().header("x-amz-copy-source", "/" + bucket + "/old?versionId=null")+ .when().put("/" + bucket + "/copy").then().statusCode(200);+ given().when().get("/" + bucket + "/copy").then().statusCode(200).body(equalTo("old"));++ // "new", written with versioning on, has no null version, and its current version is not+ // one: each request naming the null version fails as for any missing version.+ String added = "/" + bucket + "/new";+ Matcher<String> noSuchVersion = containsString("<Code>NoSuchVersion</Code>");+ given().queryParam("versionId", "null").when().get(added).then().statusCode(404).body(noSuchVersion);+ given().queryParam("versionId", "null").when().head(added).then().statusCode(404);+ given().queryParam("versionId", "null").header("x-amz-object-attributes", "ObjectSize")+ .when().get(added + "?attributes").then().statusCode(404).body(noSuchVersion);+ given().queryParam("versionId", "null").when().get(added + "?acl").then().statusCode(404).body(noSuchVersion);+ given().queryParam("versionId", "null").header("x-amz-acl", "private")+ .when().put(added + "?acl").then().statusCode(404).body(noSuchVersion);+ given().queryParam("versionId", "null").queryParam("annotationName", "labels").body("x")+ .when().put(added + "?annotation").then().statusCode(404)+ .body(containsString("<Code>NoSuchKey</Code>"));+ given().header("x-amz-copy-source", "/" + bucket + "/new?versionId=null")+ .when().put("/" + bucket + "/copy-of-new").then().statusCode(404).body(noSuchVersion);+ given().when().get(added).then().statusCode(200).body(equalTo("new"));+ }++ @Test+ @Order(25)+ void retentionAndLegalHoldFindTheNullVersion() {+ // Object Lock enabled on a bucket that already holds a null version, which keeps it.+ String bucket = "versioned-null-version-lock-test";+ given().when().put("/" + bucket).then().statusCode(200);+ given().body("old").when().put("/" + bucket + "/old").then().statusCode(200);+ given().body("<VersioningConfiguration><Status>Enabled</Status></VersioningConfiguration>")+ .when().put("/" + bucket + "?versioning").then().statusCode(200);+ given().body("<ObjectLockConfiguration><ObjectLockEnabled>Enabled</ObjectLockEnabled></ObjectLockConfiguration>")+ .when().put("/" + bucket + "?object-lock").then().statusCode(200);+ given().body("new").when().put("/" + bucket + "/new").then().statusCode(200);+ String retention = "<Retention><Mode>GOVERNANCE</Mode>"+ + "<RetainUntilDate>2031-01-01T00:00:00Z</RetainUntilDate></Retention>";+ String legalHold = "<LegalHold><Status>OFF</Status></LegalHold>";++ String old = "/" + bucket + "/old";+ given().queryParam("versionId", "null").body(retention).when().put(old + "?retention").then().statusCode(200);+ given().queryParam("versionId", "null").when().get(old + "?retention")+ .then().statusCode(200).body(containsString("<Mode>GOVERNANCE</Mode>"));+ given().queryParam("versionId", "null").body(legalHold).when().put(old + "?legal-hold").then().statusCode(200);+ given().queryParam("versionId", "null").when().get(old + "?legal-hold")+ .then().statusCode(200).body(containsString("<Status>OFF</Status>"));++ String added = "/" + bucket + "/new";+ Matcher<String> noSuchVersion = containsString("<Code>NoSuchVersion</Code>");+ given().queryParam("versionId", "null").body(retention).when().put(added + "?retention")+ .then().statusCode(404).body(noSuchVersion);+ given().queryParam("versionId", "null").when().get(added + "?retention")+ .then().statusCode(404).body(noSuchVersion);+ given().queryParam("versionId", "null").body(legalHold).when().put(added + "?legal-hold")+ .then().statusCode(404).body(noSuchVersion);+ given().queryParam("versionId", "null").when().get(added + "?legal-hold")+ .then().statusCode(404).body(noSuchVersion);++ given().queryParam("versionId", "null").header("x-amz-bypass-governance-retention", "true")+ .when().delete(old).then().statusCode(204);+ }+private static String tagging(String value) {return "<Tagging><TagSet><Tag><Key>version</Key><Value>" + value + "</Value></Tag></TagSet></Tagging>";}diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3VersioningServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3VersioningServiceTest.javaindex 5c1fa41b9a..39e655aac7 100644--- a/src/test/java/io/github/hectorvent/floci/services/s3/S3VersioningServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3VersioningServiceTest.java@@ -382,14 +382,12 @@ class S3VersioningServiceTest {for (Runnable request : List.<Runnable>of(() -> s3Service.getObjectTaggingResult("versioned-bucket", "new", "null"),() -> s3Service.putObjectTagging("versioned-bucket", "new", "null", Map.of("version", "other")),- () -> s3Service.deleteObjectTagging("versioned-bucket", "new", "null"))) {+ () -> s3Service.deleteObjectTagging("versioned-bucket", "new", "null"),+ () -> s3Service.getObjectTagging("versioned-bucket", "new", "null"))) {AwsException e = assertThrows(AwsException.class, request::run);assertEquals("NoSuchVersion", e.getErrorCode());}assertEquals(Map.of("version", "current"), s3Service.getObjectTagging("versioned-bucket", "new"));- // The condition context's lookup still takes "null" as the current version, which is what- // GetObject serves for it.- assertEquals(Map.of("version", "current"), s3Service.getObjectTagging("versioned-bucket", "new", "null"));// An object written while versioning is suspended is the null version too, above the// versions written before it.