feat(s3): track archived object restore state (#8166)

* feat(s3): track archived object restore state

* fix(s3): validate restore options and report version restore status
This commit is contained in:
Jimmy Liu Jia authored and GitHub committed 2026-11-13 00:08:10 -04:00
1 parent c3551d351e
commit 1686f29e04
11 files changed
+777 -15

No files matched your search

+1 -1
View File
@@ -31,7 +31,7 @@
| **Inventory** | PutBucketInventoryConfiguration, GetBucketInventoryConfiguration, ListBucketInventoryConfigurations, DeleteBucketInventoryConfiguration |
| **Replication** | PutBucketReplication, GetBucketReplication, DeleteBucketReplication |
**RestoreObject** is accepted but stubbed: Floci validates the request and returns `202 Accepted`, but no restore state machine runs.
**RestoreObject** tracks temporary restore state for GLACIER and DEEP_ARCHIVE objects per version. HeadObject and GetObject report `x-amz-restore`; ListObjects, ListObjectsV2, and ListObjectVersions report `RestoreStatus` when requested with `x-amz-optional-object-attributes: RestoreStatus`. New restores return 202, while extending a completed restore returns 200. Restores complete immediately by default; `FLOCI_SERVICES_S3_RESTORE_COMPLETION_DELAY_SECONDS` sets a delay for polling workflows. The temporary copy expires at the next UTC midnight after its requested days elapse from completion. Floci still allows GetObject on archived objects before restoration and after the temporary copy expires.
**Replication** is configuration-only: the replication configuration is stored on the bucket and round-trips through `GetBucketReplication`, but no objects are actually replicated.
@@ -1553,6 +1553,10 @@ public interface EmulatorConfig {
@WithDefault("false")
boolean globalBucketNamespace();
/** Seconds before RestoreObject reports a completed temporary copy. */
@WithDefault("0")
long restoreCompletionDelaySeconds();
/**
* Run the background sweep that applies bucket lifecycle expiration rules: Expiration,
* NoncurrentVersionExpiration and AbortIncompleteMultipartUpload. When off, rules are
@@ -61,6 +61,7 @@ import org.jboss.resteasy.reactive.server.ServerExceptionMapper;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
@@ -633,7 +634,7 @@ public class S3Controller {
if (params.has("versions")) {
s3Service.authorizeBucketRead(bucket, "s3:ListBucketVersions", authorization);
return handleListObjectVersions(bucket, prefix, delimiter, maxKeys, keyMarker, versionIdMarker,
encodingType);
encodingType, httpHeaders);
}
if (params.has("location")) {
s3Service.authorizeBucketRead(bucket, "s3:GetBucketLocation", authorization);
@@ -776,6 +777,7 @@ public class S3Controller {
List<S3Object> objects = result.objects();
List<String> commonPrefixes = result.commonPrefixes();
boolean v2 = "2".equals(listType);
boolean includeRestoreStatus = includesRestoreStatus(httpHeaders);
String bucketOwnerAccount = (v1 || Boolean.parseBoolean(params.first("fetch-owner")))
? s3Service.getBucketOwnerAccountId(bucket) : null;
boolean ownershipEnforced = bucketOwnerAccount != null && s3Service.bucketOwnershipIsEnforced(bucket);
@@ -805,6 +807,9 @@ public class S3Controller {
.elem("ETag", obj.getETag())
.elem("Size", obj.getSize())
.elem("StorageClass", obj.getStorageClass());
if (includeRestoreStatus) {
appendRestoreStatus(xml, obj);
}
if (bucketOwnerAccount != null) {
xml.start("Owner")
.elem("ID", AwsCanonicalUserId.forAccount(S3Service.effectiveObjectOwnerAccount(
@@ -1729,8 +1734,9 @@ public class S3Controller {
if (hasQueryParam(uriInfo, "restore")) {
checkVersionId(bucket, ResteasyRequests.queryParameters(uriInfo).getFirst("versionId"));
s3Service.authorizeObjectWrite(bucket, key, "s3:RestoreObject", authorization);
s3Service.restoreObject(bucket, key, versionId, new String(body, StandardCharsets.UTF_8));
return Response.accepted().build();
boolean started = s3Service.restoreObject(bucket, key, versionId,
new String(body, StandardCharsets.UTF_8));
return started ? Response.accepted().build() : Response.ok().build();
}
if (hasQueryParam(uriInfo, "select")) {
@@ -2181,7 +2187,8 @@ public class S3Controller {
}
private Response handleListObjectVersions(String bucket, String prefix, String delimiter, String maxKeys,
String keyMarker, String versionIdMarker, String encodingType) {
String keyMarker, String versionIdMarker, String encodingType,
HttpHeaders httpHeaders) {
if (hasText(versionIdMarker) && !hasText(keyMarker)) {
throw new AwsException("InvalidArgument",
"A version-id marker cannot be specified without a key marker.", 400);
@@ -2189,6 +2196,7 @@ public class S3Controller {
int max = resolveMaxKeys(maxKeys);
S3Service.ListVersionsResult result =
s3Service.listObjectVersions(bucket, prefix, delimiter, max, keyMarker, versionIdMarker);
boolean includeRestoreStatus = includesRestoreStatus(httpHeaders);
XmlBuilder xml = new XmlBuilder()
.raw("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
.start("ListVersionsResult", AwsNamespaces.S3)
@@ -2222,8 +2230,11 @@ public class S3Controller {
.elem("LastModified", ISO_FORMAT.format(obj.getLastModified()))
.elem("ETag", obj.getETag())
.elem("Size", obj.getSize())
.elem("StorageClass", obj.getStorageClass())
.end("Version");
.elem("StorageClass", obj.getStorageClass());
if (includeRestoreStatus) {
appendRestoreStatus(xml, obj);
}
xml.end("Version");
}
}
for (String cp : result.commonPrefixes()) {
@@ -2238,6 +2249,24 @@ public class S3Controller {
return Response.ok(xml.build()).type(MediaType.APPLICATION_XML).build();
}
private static boolean includesRestoreStatus(HttpHeaders httpHeaders) {
String optionalAttributes = httpHeaders.getHeaderString("x-amz-optional-object-attributes");
return optionalAttributes != null && Arrays.stream(optionalAttributes.split(","))
.map(String::trim).anyMatch("RestoreStatus"::equals);
}
private void appendRestoreStatus(XmlBuilder xml, S3Object obj) {
S3Service.RestoreStatus restore = s3Service.restoreStatus(obj);
if (restore != null) {
xml.start("RestoreStatus")
.elem("IsRestoreInProgress", restore.inProgress());
if (restore.expiryDate() != null) {
xml.elem("RestoreExpiryDate", DateTimeFormatter.ISO_INSTANT.format(restore.expiryDate()));
}
xml.end("RestoreStatus");
}
}
// --- Notification Configuration ---
private Response handleGetBucketNotification(String bucket) {
@@ -3176,6 +3205,14 @@ public class S3Controller {
if (obj.getStorageClass() != null) {
resp.header("x-amz-storage-class", obj.getStorageClass());
}
S3Service.RestoreStatus restore = s3Service.restoreStatus(obj);
if (restore != null) {
String header = "ongoing-request=\"" + restore.inProgress() + "\"";
if (restore.expiryDate() != null) {
header += ", expiry-date=\"" + rfc822(restore.expiryDate()) + "\"";
}
resp.header("x-amz-restore", header);
}
String contentEncoding = overrides.contentEncoding() != null ? overrides.contentEncoding() : obj.getContentEncoding();
if (contentEncoding != null) {
resp.header("Content-Encoding", contentEncoding);
@@ -67,6 +67,8 @@ import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.security.MessageDigest;
import java.time.Clock;
import java.time.DateTimeException;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
@@ -286,6 +288,8 @@ public class S3Service implements Resettable, ResourceProvider {
private final IamService iamService;
private final boolean globalBucketNamespace;
private final IamPolicyEvaluator policyEvaluator;
private final Clock clock;
private final long restoreCompletionDelaySeconds;
@Inject
public S3Service(StorageFactory storageFactory, EmulatorConfig config,
@@ -295,7 +299,7 @@ public class S3Service implements Resettable, ResourceProvider {
Event<S3ObjectUpdatedEvent> s3UpdatedEvent,
RegionResolver regionResolver,
ObjectMapper objectMapper,
IamService iamService) {
IamService iamService, Clock clock) {
this(
storageFactory.create("s3", "s3-buckets.json",
new TypeReference<Map<String, Bucket>>() {
@@ -316,10 +320,23 @@ public class S3Service implements Resettable, ResourceProvider {
regionResolver,
config.effectiveBaseUrl(), objectMapper,
config.services().s3().enforceAuth(), config.services().iam().enforcementEnabled(), iamService,
config.services().s3().globalBucketNamespace()
config.services().s3().globalBucketNamespace(), clock,
config.services().s3().restoreCompletionDelaySeconds()
);
}
public S3Service(StorageFactory storageFactory, EmulatorConfig config,
SqsService sqsService, SnsService snsService,
Instance<LambdaService> lambdaServiceProvider,
EventBridgeService eventBridgeService,
Event<S3ObjectUpdatedEvent> s3UpdatedEvent,
RegionResolver regionResolver,
ObjectMapper objectMapper,
IamService iamService) {
this(storageFactory, config, sqsService, snsService, lambdaServiceProvider,
eventBridgeService, s3UpdatedEvent, regionResolver, objectMapper, iamService, Clock.systemUTC());
}
/**
* Package-private constructor for testing.
*/
@@ -331,6 +348,15 @@ public class S3Service implements Resettable, ResourceProvider {
null, "http://localhost:4566", new ObjectMapper(), false, false, null, false);
}
S3Service(StorageBackend<String, Bucket> bucketStore,
StorageBackend<String, S3Object> objectStore,
Path dataRoot, boolean inMemory, Clock clock, long restoreCompletionDelaySeconds) {
this(bucketStore, objectStore, defaultAnnotationStore(), defaultAccountPublicAccessBlockStore(),
dataRoot, inMemory, null, null, null, null, null, null, null,
null, "http://localhost:4566", new ObjectMapper(), false, false, null, false,
clock, restoreCompletionDelaySeconds);
}
S3Service(StorageBackend<String, Bucket> bucketStore,
StorageBackend<String, S3Object> objectStore,
Path dataRoot, boolean inMemory,
@@ -402,6 +428,26 @@ public class S3Service implements Resettable, ResourceProvider {
RegionResolver regionResolver, String baseUrl, ObjectMapper objectMapper,
boolean enforceAuth, boolean enforceIam, IamService iamService,
boolean globalBucketNamespace) {
this(bucketStore, objectStore, annotationStore, accountPublicAccessBlockStore,
dataRoot, inMemory, sqsService, snsService, lambdaService, lambdaServiceProvider,
lambdaInvoker, eventBridgeService, s3UpdatedEvent, regionResolver, baseUrl,
objectMapper, enforceAuth, enforceIam, iamService, globalBucketNamespace,
Clock.systemUTC(), 0);
}
private S3Service(StorageBackend<String, Bucket> bucketStore,
StorageBackend<String, S3Object> objectStore,
AccountAwareStorageBackend<ObjectAnnotation> annotationStore,
AccountAwareStorageBackend<String> accountPublicAccessBlockStore,
Path dataRoot, boolean inMemory, SqsService sqsService, SnsService snsService,
LambdaService lambdaService,
Instance<LambdaService> lambdaServiceProvider,
LambdaInvoker lambdaInvoker,
EventBridgeService eventBridgeService,
Event<S3ObjectUpdatedEvent> s3UpdatedEvent,
RegionResolver regionResolver, String baseUrl, ObjectMapper objectMapper,
boolean enforceAuth, boolean enforceIam, IamService iamService,
boolean globalBucketNamespace, Clock clock, long restoreCompletionDelaySeconds) {
this.bucketStore = bucketStore;
this.objectStore = objectStore;
this.annotationStore = annotationStore;
@@ -423,6 +469,8 @@ public class S3Service implements Resettable, ResourceProvider {
this.iamService = iamService;
this.globalBucketNamespace = globalBucketNamespace;
this.policyEvaluator = new IamPolicyEvaluator(objectMapper);
this.clock = clock;
this.restoreCompletionDelaySeconds = Math.max(0, restoreCompletionDelaySeconds);
if (!inMemory) {
try {
Files.createDirectories(dataRoot);
@@ -6798,10 +6846,116 @@ public class S3Service implements Resettable, ResourceProvider {
.build();
}
public void restoreObject(String bucketName, String key, String versionId, String restoreXml) {
// Validation only - stub implementation
getObject(bucketName, key, versionId);
LOG.infov("Restored object: {0}/{1} (stub)", bucketName, key);
public record RestoreStatus(boolean inProgress, Instant expiryDate) { }
public RestoreStatus restoreStatus(S3Object object) {
return restoreStatus(object, clock.instant());
}
private static RestoreStatus restoreStatus(S3Object object, Instant now) {
Instant completedAt = object.getRestoreCompletionAt();
Instant expiresAt = object.getRestoreExpiryAt();
if (completedAt == null || expiresAt == null || !now.isBefore(expiresAt)) {
return null;
}
return now.isBefore(completedAt)
? new RestoreStatus(true, null)
: new RestoreStatus(false, expiresAt);
}
/** Returns true for a newly started restore, false when extending a completed restore. */
public boolean restoreObject(String bucketName, String key, String versionId, String restoreXml) {
AccountAwareStorageBackend.OwnedEntry<Bucket> ownedBucket = resolveBucketEntry(bucketName)
.orElseThrow(() -> new AwsException("NoSuchBucket",
"The specified bucket does not exist.", 404));
synchronized (ownedBucket.value()) {
S3Object object = copyObject(requireStoredObject(ownedBucket, bucketName, key, versionId));
int days = restoreDays(restoreXml, object.getStorageClass());
if (!"GLACIER".equals(object.getStorageClass()) && !"DEEP_ARCHIVE".equals(object.getStorageClass())) {
throw new AwsException("ObjectAlreadyInActiveTierError",
"This operation is not valid for objects in the active storage tier.", 403);
}
Instant now = clock.instant();
RestoreStatus status = restoreStatus(object, now);
if (status != null && status.inProgress()) {
throw new AwsException("RestoreAlreadyInProgress", "Object restore is already in progress.", 409);
}
boolean started = status == null;
try {
Instant completedAt = started ? now.plusSeconds(restoreCompletionDelaySeconds) : now;
Instant expiration = completedAt.plus(days, ChronoUnit.DAYS);
Instant midnight = expiration.truncatedTo(ChronoUnit.DAYS);
object.setRestoreCompletionAt(completedAt);
// S3 rounds the temporary copy's expiry up to the next UTC midnight.
object.setRestoreExpiryAt(expiration.equals(midnight)
? midnight : midnight.plus(1, ChronoUnit.DAYS));
} catch (DateTimeException | ArithmeticException e) {
throw malformedRestoreRequest();
}
putObjectMetadataForAccount(ownedBucket.account(), bucketName, key, object);
return started;
}
}
private static int restoreDays(String restoreXml, String storageClass) {
XmlParser.XmlElement root = XmlParser.parseDocumentElementTree(restoreXml);
if (root == null || !"RestoreRequest".equals(root.name()) || !root.text().isEmpty()
|| root.count("Days") != 1
|| root.count("Type") != 0 || root.count("SelectParameters") != 0
|| root.count("OutputLocation") != 0 || root.count("Tier") > 1
|| root.count("GlacierJobParameters") > 1 || root.count("Description") > 1
|| root.children().stream().anyMatch(child -> !Set.of("Days", "Tier",
"GlacierJobParameters", "Description").contains(child.name()))) {
throw malformedRestoreRequest();
}
XmlParser.XmlElement daysElement = root.child("Days");
if (!daysElement.children().isEmpty()) {
throw malformedRestoreRequest();
}
XmlParser.XmlElement tier = root.child("Tier");
boolean expedited = tier != null && "Expedited".equals(tier.text());
if (tier != null) {
validateRestoreTier(tier);
}
XmlParser.XmlElement glacierJobParameters = root.child("GlacierJobParameters");
if (glacierJobParameters != null) {
if (!glacierJobParameters.text().isEmpty() || glacierJobParameters.children().size() != 1
|| glacierJobParameters.count("Tier") != 1) {
throw malformedRestoreRequest();
}
XmlParser.XmlElement glacierTier = glacierJobParameters.child("Tier");
validateRestoreTier(glacierTier);
expedited |= "Expedited".equals(glacierTier.text());
}
XmlParser.XmlElement description = root.child("Description");
if (description != null && !description.children().isEmpty()) {
throw malformedRestoreRequest();
}
if ("DEEP_ARCHIVE".equals(storageClass) && expedited) {
throw new AwsException("InvalidArgument",
"Expedited retrievals are not supported for S3 Glacier Deep Archive.", 400);
}
try {
int days = Integer.parseInt(daysElement.text());
if (days > 0) {
return days;
}
} catch (NumberFormatException ignored) {
// Fall through to the same protocol error as non-positive Days.
}
throw malformedRestoreRequest();
}
private static void validateRestoreTier(XmlParser.XmlElement tier) {
if (!tier.children().isEmpty() || !Set.of("Standard", "Bulk", "Expedited").contains(tier.text())) {
throw malformedRestoreRequest();
}
}
private static AwsException malformedRestoreRequest() {
return new AwsException("MalformedXML",
"The XML you provided was not well-formed or did not validate against our published schema.", 400);
}
private static String defaultAclXml(String ownerAccount, String displayName) {
@@ -34,6 +34,8 @@ public class S3Object {
private Instant lastModified;
private String eTag;
private String storageClass;
private Instant restoreCompletionAt;
private Instant restoreExpiryAt;
private S3Checksum checksum;
private List<Part> parts;
private String versionId;
@@ -110,6 +112,8 @@ public class S3Object {
this.lastModified = source.lastModified;
this.eTag = source.eTag;
this.storageClass = source.storageClass;
this.restoreCompletionAt = source.restoreCompletionAt;
this.restoreExpiryAt = source.restoreExpiryAt;
this.checksum = source.checksum == null ? null : source.checksum.copy();
this.parts = Part.copyAll(source.parts);
this.versionId = source.versionId;
@@ -173,6 +177,12 @@ public class S3Object {
public String getStorageClass() { return storageClass; }
public void setStorageClass(String storageClass) { this.storageClass = storageClass; }
public Instant getRestoreCompletionAt() { return restoreCompletionAt; }
public void setRestoreCompletionAt(Instant restoreCompletionAt) { this.restoreCompletionAt = restoreCompletionAt; }
public Instant getRestoreExpiryAt() { return restoreExpiryAt; }
public void setRestoreExpiryAt(Instant restoreExpiryAt) { this.restoreExpiryAt = restoreExpiryAt; }
public S3Checksum getChecksum() { return checksum; }
public void setChecksum(S3Checksum checksum) { this.checksum = checksum; }
+1
View File
@@ -433,6 +433,7 @@ floci:
enforce-auth: false
default-presign-expiry-seconds: 3600
global-bucket-namespace: false
restore-completion-delay-seconds: 0 # FLOCI_SERVICES_S3_RESTORE_COMPLETION_DELAY_SECONDS
lifecycle-sweep-enabled: true # FLOCI_SERVICES_S3_LIFECYCLE_SWEEP_ENABLED - apply lifecycle expiration rules in the background
lifecycle-sweep-interval-seconds: 60 # FLOCI_SERVICES_S3_LIFECYCLE_SWEEP_INTERVAL_SECONDS
dynamodb:
@@ -134,7 +134,8 @@ class S3ObjectOperationsIamEnforcementIntegrationTest {
@Test
void restoringAnObjectNeedsRestoreObject() {
Fixture f = new Fixture("restore", false);
f.seed("a/archived");
f.admin().header("x-amz-storage-class", "GLACIER").header("x-amz-tagging", "env=a")
.body("id,name\n1,one\n").when().put(f.path("a/archived")).then().statusCode(200);
f.policy(f.allow("s3:GetObject", "s3:PutObject"));
denied(f.restore("a/archived"), "s3:RestoreObject");
@@ -14,7 +14,9 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -241,6 +243,52 @@ class S3ObjectIndexJournalTest {
}
}
@Test
void restoredVersionsAndTheCurrentAliasSurviveJournalReplay() throws IOException {
Path directory = root.resolve("live");
Path afterCrash = root.resolve("after-crash");
Instant started = Instant.parse("2026-11-12T12:00:00Z");
String request = "<RestoreRequest><Days>1</Days></RestoreRequest>";
String older;
String current;
StorageFactory first = newFactory(directory);
try {
S3Service service = newService(first, directory, Clock.fixed(started, ZoneOffset.UTC), 60);
service.createBucket(VERSIONED_BUCKET, REGION);
service.putBucketVersioning(VERSIONED_BUCKET, "Enabled");
older = service.putObject(VERSIONED_BUCKET, key(0), body(0), "text/plain", Map.of(),
"GLACIER", null, null, null).getVersionId();
current = service.putObject(VERSIONED_BUCKET, key(0), body(1), "text/plain", Map.of(),
"GLACIER", null, null, null).getVersionId();
assertTrue(service.restoreObject(VERSIONED_BUCKET, key(0), older, request));
assertTrue(service.restoreObject(VERSIONED_BUCKET, key(0), current, request));
copyAsLeftByAKill(directory, afterCrash);
} finally {
first.shutdownAll();
}
StorageFactory second = newFactory(afterCrash);
try {
S3Service ongoing = newService(second, afterCrash,
Clock.fixed(started.plusSeconds(30), ZoneOffset.UTC), 60);
assertTrue(ongoing.restoreStatus(ongoing.headObject(VERSIONED_BUCKET, key(0), older)).inProgress());
assertTrue(ongoing.restoreStatus(ongoing.headObject(VERSIONED_BUCKET, key(0), current)).inProgress());
assertTrue(ongoing.restoreStatus(ongoing.headObject(VERSIONED_BUCKET, key(0))).inProgress());
S3Service completed = newService(second, afterCrash,
Clock.fixed(started.plusSeconds(60), ZoneOffset.UTC), 60);
Instant expiry = Instant.parse("2026-11-14T00:00:00Z");
assertEquals(new S3Service.RestoreStatus(false, expiry),
completed.restoreStatus(completed.headObject(VERSIONED_BUCKET, key(0), older)));
assertEquals(new S3Service.RestoreStatus(false, expiry),
completed.restoreStatus(completed.headObject(VERSIONED_BUCKET, key(0), current)));
assertEquals(new S3Service.RestoreStatus(false, expiry),
completed.restoreStatus(completed.headObject(VERSIONED_BUCKET, key(0))));
} finally {
second.shutdownAll();
}
}
/**
* The storage directory as a process killed now would leave it, with no shutdown compaction.
* Replaying a copy keeps the restarted factory from sharing the journal with the live writer.
@@ -271,6 +319,10 @@ class S3ObjectIndexJournalTest {
}
private static S3Service newService(StorageFactory factory, Path storage) {
return newService(factory, storage, Clock.systemUTC(), 0);
}
private static S3Service newService(StorageFactory factory, Path storage, Clock clock, long delaySeconds) {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.storage().persistentPath()).thenReturn(storage.toString());
when(config.storage().mode()).thenReturn("persistent");
@@ -278,8 +330,9 @@ class S3ObjectIndexJournalTest {
when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
when(config.services().s3().enforceAuth()).thenReturn(false);
when(config.services().s3().globalBucketNamespace()).thenReturn(false);
when(config.services().s3().restoreCompletionDelaySeconds()).thenReturn(delaySeconds);
return new S3Service(factory, config, null, null, null, null, null,
new RegionResolver(REGION, ACCOUNT), new ObjectMapper(), null);
new RegionResolver(REGION, ACCOUNT), new ObjectMapper(), null, clock);
}
private static StorageFactory newFactory(Path storage) {
@@ -0,0 +1,315 @@
package io.floci.aws.services.s3;
import io.floci.aws.core.common.XmlParser;
import io.floci.aws.testing.MutableClock;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
@QuarkusTest
@TestProfile(S3RestoreStateIntegrationTest.DelayedRestoreProfile.class)
class S3RestoreStateIntegrationTest {
private static final String RESTORE_REQUEST = "<RestoreRequest><Days>1</Days></RestoreRequest>";
private static final String COMPLETED_RESTORE_HEADER =
"ongoing-request=\"false\", expiry-date=\"Sat, 03 Jan 2026 00:00:00 GMT\"";
@Inject
MutableClock clock;
public static final class DelayedRestoreProfile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of("floci.services.s3.restore-completion-delay-seconds", "60");
}
}
@BeforeEach
void resetClockBeforeTest() {
clock.reset();
}
@AfterEach
void resetClockAfterTest() {
clock.reset();
}
@Test
void restoreStateFollowsTheVersionThroughHeadGetAndList() {
try (Fixture fixture = new Fixture()) {
String olderPath = fixture.path() + "?versionId=" + fixture.olderVersion();
String currentPath = fixture.path() + "?versionId=" + fixture.currentVersion();
given().when().head(olderPath).then().statusCode(200).header("x-amz-restore", nullValue());
given().when().head(currentPath).then().statusCode(200).header("x-amz-restore", nullValue());
given().body(RESTORE_REQUEST).when().post(olderPath + "&restore").then().statusCode(202);
given().when().head(olderPath).then().statusCode(200)
.header("x-amz-restore", equalTo("ongoing-request=\"true\""));
given().when().get(olderPath).then().statusCode(200)
.header("x-amz-restore", equalTo("ongoing-request=\"true\""));
given().when().head(currentPath).then().statusCode(200).header("x-amz-restore", nullValue());
given().body(RESTORE_REQUEST).when().post(currentPath + "&restore").then().statusCode(202);
given().when().head(currentPath).then().statusCode(200)
.header("x-amz-restore", equalTo("ongoing-request=\"true\""));
given().header("x-amz-optional-object-attributes", "RestoreStatus")
.queryParam("list-type", "2").when().get(fixture.bucketPath()).then().statusCode(200)
.body(containsString("<IsRestoreInProgress>true</IsRestoreInProgress>"));
given().queryParam("list-type", "2").when().get(fixture.bucketPath()).then().statusCode(200)
.body(not(containsString("<RestoreStatus>")));
given().header("x-amz-optional-object-attributes", "RestoreStatus")
.when().get(fixture.bucketPath()).then().statusCode(200)
.body(containsString("<IsRestoreInProgress>true</IsRestoreInProgress>"));
given().when().get(fixture.bucketPath()).then().statusCode(200)
.body(not(containsString("<RestoreStatus>")));
clock.advance(Duration.ofSeconds(61));
given().when().head(currentPath).then().statusCode(200)
.header("x-amz-restore", equalTo(COMPLETED_RESTORE_HEADER));
given().when().get(currentPath).then().statusCode(200)
.header("x-amz-restore", equalTo(COMPLETED_RESTORE_HEADER))
.body(equalTo("current"));
given().when().get(olderPath).then().statusCode(200)
.header("x-amz-restore", equalTo(COMPLETED_RESTORE_HEADER))
.body(equalTo("older"));
given().header("x-amz-optional-object-attributes", "RestoreStatus")
.queryParam("list-type", "2").when().get(fixture.bucketPath()).then().statusCode(200)
.body(containsString("<IsRestoreInProgress>false</IsRestoreInProgress>"))
.body(containsString("<RestoreExpiryDate>2026-01-03T00:00:00Z</RestoreExpiryDate>"));
given().body(RESTORE_REQUEST).when().post(olderPath + "&restore").then().statusCode(200);
given().body(RESTORE_REQUEST).when().post(currentPath + "&restore").then().statusCode(200);
}
}
@Test
void repeatedRestoreWhileInProgressIsRejected() {
try (Fixture fixture = new Fixture()) {
String path = fixture.path() + "?versionId=" + fixture.currentVersion() + "&restore";
given().body(RESTORE_REQUEST).when().post(path).then().statusCode(202);
given().body(RESTORE_REQUEST).when().post(path).then().statusCode(409)
.body("Error.Code", equalTo("RestoreAlreadyInProgress"));
}
}
@Test
void listVersionsIncludesRestoreStatusOnlyWhenRequested() {
try (Fixture fixture = new Fixture()) {
String olderPath = fixture.path() + "?versionId=" + fixture.olderVersion();
given().body(RESTORE_REQUEST).when().post(olderPath + "&restore").then().statusCode(202);
String deleteMarker = given().when().delete(fixture.path()).then().statusCode(204)
.extract().header("x-amz-version-id");
fixture.trackVersion(deleteMarker);
String withoutAttribute = given().when().get(fixture.bucketPath() + "?versions")
.then().statusCode(200).extract().asString();
assertEquals(0, XmlParser.parseDocumentElementTree(withoutAttribute).children().stream()
.filter(child -> "Version".equals(child.name()))
.filter(version -> version.child("RestoreStatus") != null).count());
String withAttribute = given().header("x-amz-optional-object-attributes", "RestoreStatus")
.when().get(fixture.bucketPath() + "?versions")
.then().statusCode(200).extract().asString();
XmlParser.XmlElement result = XmlParser.parseDocumentElementTree(withAttribute);
assertEquals(1, result.count("DeleteMarker"));
assertNull(result.child("DeleteMarker").child("RestoreStatus"));
assertEquals(2, result.count("Version"));
for (XmlParser.XmlElement version : result.children()) {
if (!"Version".equals(version.name())) {
continue;
}
XmlParser.XmlElement status = version.child("RestoreStatus");
if (fixture.olderVersion().equals(version.child("VersionId").text())) {
assertNotNull(status);
assertEquals("true", status.child("IsRestoreInProgress").text());
assertNull(status.child("RestoreExpiryDate"));
} else {
assertEquals(fixture.currentVersion(), version.child("VersionId").text());
assertNull(status);
}
}
}
}
@Test
void deepArchiveRejectsExpeditedRestoreWithoutStateChange() {
try (Fixture fixture = new Fixture()) {
String path = fixture.bucketPath() + "/deep.txt";
String version = given().header("x-amz-storage-class", "DEEP_ARCHIVE").body("deep")
.when().put(path).then().statusCode(200).extract().header("x-amz-version-id");
try {
for (String request : List.of(
"<RestoreRequest><Days>1</Days><Tier>Expedited</Tier></RestoreRequest>",
"<RestoreRequest><Days>1</Days><GlacierJobParameters><Tier>Expedited</Tier>"
+ "</GlacierJobParameters></RestoreRequest>")) {
given().body(request).when().post(path + "?versionId=" + version + "&restore")
.then().statusCode(400);
given().when().head(path + "?versionId=" + version).then().statusCode(200)
.header("x-amz-restore", nullValue());
}
} finally {
given().when().delete(path + "?versionId=" + version).then().statusCode(204);
}
}
}
@Test
void mixedTextInRestoreContainersIsRejectedWithoutStateChange() {
try (Fixture fixture = new Fixture()) {
String path = fixture.path() + "?versionId=" + fixture.currentVersion();
for (String request : List.of(
"<RestoreRequest>junk<Days>1</Days></RestoreRequest>",
"<RestoreRequest><Days>1</Days><GlacierJobParameters>junk<Tier>Standard</Tier>"
+ "</GlacierJobParameters></RestoreRequest>")) {
given().body(request).when().post(path + "&restore").then().statusCode(400)
.body("Error.Code", equalTo("MalformedXML"));
given().when().head(path).then().statusCode(200).header("x-amz-restore", nullValue());
}
}
}
@Test
void completedRestoreHeaderPadsSingleDigitDay() {
try (Fixture fixture = new Fixture()) {
String path = fixture.path() + "?versionId=" + fixture.currentVersion();
given().body(RESTORE_REQUEST).when().post(path + "&restore").then().statusCode(202);
clock.advance(Duration.ofSeconds(61));
given().when().head(path).then().statusCode(200)
.header("x-amz-restore", equalTo(COMPLETED_RESTORE_HEADER));
}
}
@Test
void overwritingAndPromotingVersionsKeepRestoreStateWithTheVersion() {
try (Fixture fixture = new Fixture()) {
String currentPath = fixture.path() + "?versionId=" + fixture.currentVersion();
given().body(RESTORE_REQUEST).when().post(currentPath + "&restore").then().statusCode(202);
given().when().head(currentPath).then().statusCode(200)
.header("x-amz-restore", equalTo("ongoing-request=\"true\""));
String replacement = fixture.put("replacement");
given().when().head(fixture.path()).then().statusCode(200).header("x-amz-restore", nullValue());
given().when().head(currentPath).then().statusCode(200).header("x-amz-restore", notNullValue());
given().when().delete(fixture.path() + "?versionId=" + replacement).then().statusCode(204);
fixture.forget(replacement);
given().when().head(fixture.path()).then().statusCode(200).header("x-amz-restore", notNullValue());
}
}
@Test
void invalidRequestsDoNotCreateRestoreState() {
try (Fixture fixture = new Fixture()) {
String path = fixture.path() + "?versionId=" + fixture.currentVersion();
for (String invalid : List.of("<RestoreRequest/>",
"<RestoreRequest><Days>0</Days></RestoreRequest>",
"<RestoreRequest><Days>invalid</Days></RestoreRequest>",
"<RestoreRequest><Nested><Days>1</Days></Nested></RestoreRequest>",
"<RestoreRequest><Days>1</Days><Days>2</Days></RestoreRequest>",
"<RestoreRequest><Days>2147483648</Days></RestoreRequest>",
"<RestoreRequest><Days>1</Days><Unknown/></RestoreRequest>",
"<RestoreRequest><Days>1</Days><Tier>Standard</Tier><Tier>Standard</Tier></RestoreRequest>",
"<RestoreRequest><Days>1</Days><Tier>Invalid</Tier></RestoreRequest>",
"<RestoreRequest><Days>1</Days><Tier><Bogus/></Tier></RestoreRequest>",
"<RestoreRequest><Days>1</Days><GlacierJobParameters/></RestoreRequest>",
"<RestoreRequest><Days>1</Days><GlacierJobParameters><Tier>Invalid</Tier></GlacierJobParameters></RestoreRequest>",
"<RestoreRequest><Days>1</Days><GlacierJobParameters><Bogus/></GlacierJobParameters></RestoreRequest>",
"<RestoreRequest><Days>1</Days><Description><Bogus/></Description></RestoreRequest>",
"<RestoreRequest><Days>1</Days><Type>SELECT</Type></RestoreRequest>",
"<RestoreRequest><Days>1</Days><OutputLocation/></RestoreRequest>",
"<RestoreRequest><Days>1</Days>")) {
given().body(invalid).when().post(path + "&restore").then().statusCode(400)
.body("Error.Code", equalTo("MalformedXML"));
}
given().when().head(path).then().statusCode(200).header("x-amz-restore", nullValue());
given().body(RESTORE_REQUEST).when().post(fixture.bucketPath() + "/missing?restore")
.then().statusCode(404).body("Error.Code", equalTo("NoSuchKey"));
String ordinaryVersion = given().body("ordinary")
.when().put(fixture.bucketPath() + "/ordinary.txt").then().statusCode(200)
.extract().header("x-amz-version-id");
given().body(RESTORE_REQUEST).when().post(fixture.bucketPath() + "/ordinary.txt?restore")
.then().statusCode(403).body("Error.Code", equalTo("ObjectAlreadyInActiveTierError"));
given().when().head(fixture.bucketPath() + "/ordinary.txt").then().statusCode(200)
.header("x-amz-restore", nullValue());
given().when().delete(fixture.bucketPath() + "/ordinary.txt?versionId=" + ordinaryVersion)
.then().statusCode(204);
}
}
@Test
void validOptionalRestoreTiersAreAccepted() {
try (Fixture fixture = new Fixture()) {
given().body("<RestoreRequest><Days>1</Days><Tier>Standard</Tier>"
+ "<Description>test restore</Description></RestoreRequest>")
.when().post(fixture.path() + "?versionId=" + fixture.olderVersion() + "&restore")
.then().statusCode(202);
given().body("<RestoreRequest><Days>1</Days><GlacierJobParameters><Tier>Bulk</Tier>"
+ "</GlacierJobParameters></RestoreRequest>")
.when().post(fixture.path() + "?versionId=" + fixture.currentVersion() + "&restore")
.then().statusCode(202);
}
}
private static final class Fixture implements AutoCloseable {
private final String bucket = "restore-state-it-" + UUID.randomUUID().toString().substring(0, 8);
private final String path = bucketPath() + "/archived.txt";
private final List<String> versions = new ArrayList<>();
private final String olderVersion;
private final String currentVersion;
private Fixture() {
given().when().put(bucketPath()).then().statusCode(200);
given().body("<VersioningConfiguration><Status>Enabled</Status></VersioningConfiguration>")
.when().put(bucketPath() + "?versioning").then().statusCode(200);
olderVersion = put("older");
currentVersion = put("current");
}
private String put(String body) {
String version = given().header("x-amz-storage-class", "GLACIER").body(body)
.when().put(path).then().statusCode(200)
.header("x-amz-version-id", notNullValue())
.extract().header("x-amz-version-id");
versions.add(version);
return version;
}
private void forget(String version) { versions.remove(version); }
private void trackVersion(String version) { versions.add(version); }
private String bucketPath() { return "/" + bucket; }
private String path() { return path; }
private String olderVersion() { return olderVersion; }
private String currentVersion() { return currentVersion; }
@Override
public void close() {
for (int i = versions.size() - 1; i >= 0; i--) {
given().when().delete(path + "?versionId=" + versions.get(i)).then().statusCode(204);
}
given().when().delete(bucketPath()).then().statusCode(204);
}
}
}
@@ -0,0 +1,186 @@
package io.floci.aws.services.s3;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.storage.InMemoryStorage;
import io.floci.aws.services.s3.model.Bucket;
import io.floci.aws.services.s3.model.CopyObjectOptions;
import io.floci.aws.services.s3.model.S3Object;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class S3RestoreStateServiceTest {
private static final Instant START = Instant.parse("2026-11-12T12:00:00Z");
private static final Instant ONE_DAY_EXPIRY = Instant.parse("2026-11-14T00:00:00Z");
private static final String ONE_DAY = "<RestoreRequest><Days>1</Days></RestoreRequest>";
@TempDir
Path dataRoot;
@Test
void completionAndExpiryUseExactClockBoundaries() {
InMemoryStorage<String, Bucket> buckets = new InMemoryStorage<>();
InMemoryStorage<String, S3Object> objects = new InMemoryStorage<>();
S3Service start = service(buckets, objects, START, 10);
start.createBucket("archive", "us-east-1");
putArchived(start, "key");
assertNull(start.restoreStatus(start.headObject("archive", "key")));
assertTrue(start.restoreObject("archive", "key", null, ONE_DAY));
assertEquals(new S3Service.RestoreStatus(true, null),
start.restoreStatus(start.headObject("archive", "key")));
AwsException inProgress = assertThrows(AwsException.class,
() -> start.restoreObject("archive", "key", null, ONE_DAY));
assertEquals("RestoreAlreadyInProgress", inProgress.getErrorCode());
assertEquals(409, inProgress.getHttpStatus());
Instant completion = START.plusSeconds(10);
Instant expiry = ONE_DAY_EXPIRY;
S3Service beforeCompletion = service(buckets, objects, completion.minusNanos(1), 10);
assertTrue(beforeCompletion.restoreStatus(beforeCompletion.headObject("archive", "key")).inProgress());
S3Service atCompletion = service(buckets, objects, completion, 10);
assertEquals(new S3Service.RestoreStatus(false, expiry),
atCompletion.restoreStatus(atCompletion.headObject("archive", "key")));
S3Service beforeExpiry = service(buckets, objects, expiry.minusNanos(1), 10);
assertFalse(beforeExpiry.restoreStatus(beforeExpiry.headObject("archive", "key")).inProgress());
S3Service atExpiry = service(buckets, objects, expiry, 10);
assertNull(atExpiry.restoreStatus(atExpiry.headObject("archive", "key")));
assertTrue(atExpiry.restoreObject("archive", "key", null, ONE_DAY));
assertTrue(atExpiry.restoreStatus(atExpiry.headObject("archive", "key")).inProgress());
}
@Test
void exactMidnightExpiryDoesNotGainAnExtraDay() {
InMemoryStorage<String, Bucket> buckets = new InMemoryStorage<>();
InMemoryStorage<String, S3Object> objects = new InMemoryStorage<>();
Instant midnight = Instant.parse("2026-11-12T00:00:00Z");
S3Service service = service(buckets, objects, midnight, 0);
service.createBucket("archive", "us-east-1");
putArchived(service, "key");
assertTrue(service.restoreObject("archive", "key", null, ONE_DAY));
assertEquals(midnight.plus(1, ChronoUnit.DAYS),
service.restoreStatus(service.headObject("archive", "key")).expiryDate());
}
@Test
void delayCrossingMidnightStartsExpiryPeriodAtCompletion() {
InMemoryStorage<String, Bucket> buckets = new InMemoryStorage<>();
InMemoryStorage<String, S3Object> objects = new InMemoryStorage<>();
Instant request = Instant.parse("2026-11-12T23:59:30Z");
S3Service start = service(buckets, objects, request, 60);
start.createBucket("archive", "us-east-1");
putArchived(start, "key");
assertTrue(start.restoreObject("archive", "key", null, ONE_DAY));
S3Service completed = service(buckets, objects, request.plusSeconds(60), 60);
assertEquals(new S3Service.RestoreStatus(false, Instant.parse("2026-11-15T00:00:00Z")),
completed.restoreStatus(completed.headObject("archive", "key")));
}
@Test
void completedRequestExtendsOnlyTheSelectedVersion() {
InMemoryStorage<String, Bucket> buckets = new InMemoryStorage<>();
InMemoryStorage<String, S3Object> objects = new InMemoryStorage<>();
S3Service start = service(buckets, objects, START, 0);
start.createBucket("archive", "us-east-1");
start.putBucketVersioning("archive", "Enabled");
String older = putArchived(start, "key").getVersionId();
String current = putArchived(start, "key").getVersionId();
assertTrue(start.restoreObject("archive", "key", older, ONE_DAY));
assertNull(start.restoreStatus(start.headObject("archive", "key", current)));
assertTrue(start.restoreObject("archive", "key", current, ONE_DAY));
Instant later = START.plusSeconds(3_600);
S3Service extension = service(buckets, objects, later, 0);
assertFalse(extension.restoreObject("archive", "key", older,
"<RestoreRequest><Days>2</Days></RestoreRequest>"));
assertEquals(Instant.parse("2026-11-15T00:00:00Z"),
extension.restoreStatus(extension.headObject("archive", "key", older)).expiryDate());
assertEquals(ONE_DAY_EXPIRY,
extension.restoreStatus(extension.headObject("archive", "key", current)).expiryDate());
assertEquals(ONE_DAY_EXPIRY,
extension.restoreStatus(extension.headObject("archive", "key")).expiryDate());
}
@Test
void archivedNullVersionRetainsStateAfterANewNumberedVersion() {
InMemoryStorage<String, Bucket> buckets = new InMemoryStorage<>();
InMemoryStorage<String, S3Object> objects = new InMemoryStorage<>();
S3Service service = service(buckets, objects, START, 0);
service.createBucket("archive", "us-east-1");
service.putBucketVersioning("archive", "Enabled");
service.putBucketVersioning("archive", "Suspended");
putArchived(service, "key");
assertTrue(service.restoreObject("archive", "key", "null", ONE_DAY));
service.putBucketVersioning("archive", "Enabled");
putArchived(service, "key");
assertNull(service.restoreStatus(service.headObject("archive", "key")));
assertEquals(new S3Service.RestoreStatus(false, ONE_DAY_EXPIRY),
service.restoreStatus(service.headObject("archive", "key", "null")));
}
@Test
void overwriteAndPromotionKeepTheDelayedStateOnItsVersion() {
InMemoryStorage<String, Bucket> buckets = new InMemoryStorage<>();
InMemoryStorage<String, S3Object> objects = new InMemoryStorage<>();
S3Service service = service(buckets, objects, START, 10);
service.createBucket("archive", "us-east-1");
service.putBucketVersioning("archive", "Enabled");
putArchived(service, "key");
String restored = putArchived(service, "key").getVersionId();
assertTrue(service.restoreObject("archive", "key", restored, ONE_DAY));
String replacement = putArchived(service, "key").getVersionId();
assertNull(service.restoreStatus(service.headObject("archive", "key")));
assertTrue(service.restoreStatus(service.headObject("archive", "key", restored)).inProgress());
service.deleteObject("archive", "key", replacement);
assertTrue(service.restoreStatus(service.headObject("archive", "key")).inProgress());
assertTrue(service.restoreStatus(service.headObject("archive", "key", restored)).inProgress());
}
@Test
void copyIntoStandardDoesNotInheritSourceRestoreState() {
InMemoryStorage<String, Bucket> buckets = new InMemoryStorage<>();
InMemoryStorage<String, S3Object> objects = new InMemoryStorage<>();
S3Service service = service(buckets, objects, START, 0);
service.createBucket("archive", "us-east-1");
putArchived(service, "source");
assertTrue(service.restoreObject("archive", "source", null, ONE_DAY));
service.copyObject("archive", "source", "archive", "copy",
new CopyObjectOptions().withStorageClass("STANDARD"));
assertNull(service.restoreStatus(service.headObject("archive", "copy")));
assertEquals("STANDARD", service.headObject("archive", "copy").getStorageClass());
assertEquals(new S3Service.RestoreStatus(false, ONE_DAY_EXPIRY),
service.restoreStatus(service.headObject("archive", "source")));
}
private S3Service service(InMemoryStorage<String, Bucket> buckets,
InMemoryStorage<String, S3Object> objects,
Instant now, long delaySeconds) {
return new S3Service(buckets, objects, dataRoot, true,
Clock.fixed(now, ZoneOffset.UTC), delaySeconds);
}
private static S3Object putArchived(S3Service service, String key) {
return service.putObject("archive", key, "body".getBytes(StandardCharsets.UTF_8),
"text/plain", Map.of(), "GLACIER", null, null, null);
}
}
+1
View File
@@ -146,6 +146,7 @@ floci:
enforce-auth: false
default-presign-expiry-seconds: 3600
global-bucket-namespace: false
restore-completion-delay-seconds: 0
lifecycle-sweep-enabled: false # tests run the sweep themselves, so no bucket's rules apply behind another test's back
lifecycle-sweep-interval-seconds: 60
dynamodb: