fix(dynamodb): export the table as of ExportTime (#6132)

* fix(dynamodb): export the table as of ExportTime

* refactor(dynamodb): share the epoch seconds conversions

* fix(dynamodb): treat a table that is still being created as not found on export

* docs(dynamodb): note the writes made before point-in-time recovery is enabled

* fix(dynamodb): round timestamp inputs to milliseconds as AWS does

* fix(dynamodb): check the ListBackups time range limits

* fix(dynamodb): check the ListBackups ExclusiveStartBackupArn length

* refactor(dynamodb): reuse requireBackupSource for the export table lookup
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-10-22 07:31:07 -04:00
1 parent f7576eda1a
commit da66550c70
12 files changed
+396 -37

No files matched your search

@@ -102,6 +102,13 @@ class RegionScopedListsIntegrationTest {
""".formatted(table))
.when().post("/").then().statusCode(200)
.extract().path("TableDescription.TableArn");
given().header("Authorization", auth(HOME, "dynamodb"))
.header("X-Amz-Target", "DynamoDB_20120810.UpdateContinuousBackups")
.contentType(DYNAMODB_JSON)
.body("""
{"TableName": "%s", "PointInTimeRecoverySpecification": {"PointInTimeRecoveryEnabled": true}}
""".formatted(table))
.when().post("/").then().statusCode(200);
// The bucket is never created: the export job is recorded before it writes anything, and a
// missing bucket only fails the job later. Export jobs have no delete API.
String exportArn = given().header("Authorization", auth(HOME, "dynamodb"))
@@ -269,6 +269,33 @@ class DynamoDbBackupIntegrationTest {
+ "Time range lower bound must be less than or equal to upper bound"));
}
@Test
void listBackupsChecksTheTimeRangeLimits() {
String before = "Invalid Request: The supplied %s must not be before 1970-01-01T00:00:00Z";
String after = "Invalid Request: The supplied %s must not be after 5138-11-16T09:46:39.999Z";
listBackupsBetween("-0.0005", "99999999999.9994").statusCode(200);
listBackupsBetween("-0.001", null)
.statusCode(400)
.body("message", equalTo(before.formatted("TimeRangeLowerBound")));
listBackupsBetween(null, "100000000000")
.statusCode(400)
.body("message", equalTo(after.formatted("TimeRangeUpperBound")));
listBackupsBetween("-1e20", "1e20")
.statusCode(400)
.body("message", equalTo(before.formatted("TimeRangeLowerBound")));
listBackupsBetween("0", "1e400")
.statusCode(400)
.body("message", equalTo(after.formatted("TimeRangeUpperBound")));
listBackupsBetween("1e21", "1e20")
.statusCode(400)
.body("message", equalTo(after.formatted("TimeRangeLowerBound")));
listBackupsBetween("100000000000", "-0.001")
.statusCode(400)
.body("message", equalTo("One or more parameter values were invalid: "
+ "Time range lower bound must be less than or equal to upper bound"));
}
@Test
void listBackupsReportsEveryViolation() {
ddb("ListBackups", "{\"Limit\": 0, \"BackupType\": \"BAD\"}")
@@ -284,6 +311,22 @@ class DynamoDbBackupIntegrationTest {
ddb("ListBackups", "{\"ExclusiveStartBackupArn\": \"" + "x".repeat(40) + "\"}")
.statusCode(400)
.body("message", equalTo("Invalid Backup ARN"));
String shortArn = "x".repeat(36);
ddb("ListBackups", """
{"Limit": 0, "ExclusiveStartBackupArn": "%s", "BackupType": "BAD"}
""".formatted(shortArn))
.statusCode(400)
.body("message", equalTo("3 validation errors detected: Value '0' at 'limit' failed to satisfy "
+ "constraint: Member must have value greater than or equal to 1; Value '" + shortArn
+ "' at 'exclusiveStartBackupArn' failed to satisfy constraint: Member must have length "
+ "greater than or equal to 37; Value 'BAD' at 'backupType' failed to satisfy constraint: "
+ "Member must satisfy enum value set: [ALL, AWS_BACKUP, USER, SYSTEM]"));
String longArn = "x".repeat(1025);
ddb("ListBackups", "{\"ExclusiveStartBackupArn\": \"" + longArn + "\"}")
.statusCode(400)
.body("message", equalTo("1 validation error detected: Value '" + longArn + "' at "
+ "'exclusiveStartBackupArn' failed to satisfy constraint: Member must have length "
+ "less than or equal to 1024"));
}
@Test
@@ -755,4 +798,10 @@ class DynamoDbBackupIntegrationTest {
{"BackupArn": "%s", "TargetTableName": "%s", %s}
""".formatted(backupArn, target, overrides));
}
private static ValidatableResponse listBackupsBetween(String lowerBound, String upperBound) {
return ddb("ListBackups", """
{"TimeRangeLowerBound": %s, "TimeRangeUpperBound": %s}
""".formatted(lowerBound, upperBound));
}
}
@@ -2,6 +2,8 @@ package io.github.hectorvent.floci.services.dynamodb;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.path.json.JsonPath;
import io.restassured.response.ValidatableResponse;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -9,9 +11,15 @@ import org.junit.jupiter.api.Test;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.GZIPInputStream;
import static io.github.hectorvent.floci.testing.DynamoDbRequests.ddb;
import static io.github.hectorvent.floci.testing.DynamoDbRequests.decimalAt;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.*;
@@ -24,6 +32,7 @@ class DynamoDbExportIntegrationTest {
private static final String BUCKET_NAME = "export-test-bucket";
private static final String TABLE_ARN =
"arn:aws:dynamodb:us-east-1:000000000000:table/" + TABLE_NAME;
private static final String TABLE_ARN_PREFIX = "arn:aws:dynamodb:us-east-1:000000000000:table/";
private static boolean setupDone = false;
@@ -59,6 +68,7 @@ class DynamoDbExportIntegrationTest {
}
""".formatted(TABLE_NAME))
.when().post("/").then().statusCode(200);
enablePointInTimeRecovery(TABLE_NAME);
// Insert 3 items
putItem("{\"pk\": {\"S\": \"user-1\"}, \"sk\": {\"S\": \"order-001\"}, \"total\": {\"N\": \"99\"}}");
@@ -175,7 +185,7 @@ class DynamoDbExportIntegrationTest {
}
@Test
void exportTableToPointInTime_tableNotFound_returnsResourceNotFoundException() {
void exportTableToPointInTime_tableNotFound_returnsTableNotFoundException() {
given()
.header("X-Amz-Target", "DynamoDB_20120810.ExportTableToPointInTime")
.contentType(DYNAMODB_CONTENT_TYPE)
@@ -188,7 +198,9 @@ class DynamoDbExportIntegrationTest {
.when().post("/")
.then()
.statusCode(400)
.body("__type", containsString("ResourceNotFoundException"));
.body("__type", containsString("TableNotFoundException"))
.body("message", equalTo(
"Table not found: arn:aws:dynamodb:us-east-1:000000000000:table/NonExistentTable"));
}
@Test
@@ -249,8 +261,145 @@ class DynamoDbExportIntegrationTest {
}
}
@Test
void exportTimeExportsTheItemsOfThatTime() throws Exception {
String table = "ExportTimeItems";
createHashTable(table);
BigDecimal earliest = decimalAt(enablePointInTimeRecovery(table),
"/ContinuousBackupsDescription/PointInTimeRecoveryDescription/EarliestRestorableDateTime");
putHashItem(table, "k1", "v1");
BigDecimal t1 = pause();
putHashItem(table, "k1", "v2");
putHashItem(table, "k2", "v1");
exportAt(table, "export-time-earliest", earliest).statusCode(200);
ValidatableResponse atT1 = exportAt(table, "export-time-t1", t1).statusCode(200);
assertEquals(0, t1.compareTo(decimalAt(atT1, "/ExportDescription/ExportTime")));
long before = System.currentTimeMillis();
ValidatableResponse noTime = ddb("ExportTableToPointInTime", """
{"TableArn": "%s", "S3Bucket": "%s", "S3Prefix": "export-time-now"}
""".formatted(TABLE_ARN_PREFIX + table, BUCKET_NAME)).statusCode(200);
long after = System.currentTimeMillis();
BigDecimal startTime = decimalAt(noTime, "/ExportDescription/StartTime");
assertEquals(0, startTime.compareTo(decimalAt(noTime, "/ExportDescription/ExportTime")));
long startMillis = startTime.movePointRight(3).longValueExact();
assertTrue(before <= startMillis && startMillis <= after, before + " <= " + startTime + " <= " + after);
String atT1Arn = atT1.extract().path("ExportDescription.ExportArn");
assertEquals("COMPLETED", pollUntilCompleted(atT1Arn, 10_000));
assertEquals(List.of("k1=v1"), exportedItems(atT1Arn, "export-time-t1"));
String noTimeArn = noTime.extract().path("ExportDescription.ExportArn");
assertEquals("COMPLETED", pollUntilCompleted(noTimeArn, 10_000));
assertEquals(List.of("k1=v2", "k2=v1"), exportedItems(noTimeArn, "export-time-now"));
}
@Test
void exportTableToPointInTimeChecksInTheAwsOrder() throws Exception {
String table = "ExportTimeChecks";
long beforeCreate = System.currentTimeMillis();
createHashTable(table);
long afterCreate = System.currentTimeMillis();
BigDecimal future = BigDecimal.valueOf(System.currentTimeMillis() + 60_000, 3);
expectError(exportAt("ExportTimeMissing", "export-checks", future),
"TableNotFoundException", "Table not found: " + TABLE_ARN_PREFIX + "ExportTimeMissing");
expectError(exportAt(table, "export-checks", future), "InvalidExportTimeException", "Export Time is invalid");
expectError(ddb("ExportTableToPointInTime", """
{"TableArn": "%s", "S3Bucket": "%s"}
""".formatted(TABLE_ARN_PREFIX + table, BUCKET_NAME)), "PointInTimeRecoveryUnavailableException",
"Point in time recovery is not enabled for table '" + table + "'");
// EarliestRestorableDateTime is in whole seconds. Enabling in a later second puts it after the creation.
while (System.currentTimeMillis() / 1000 <= afterCreate / 1000) {
Thread.sleep(10);
}
BigDecimal earliest = decimalAt(enablePointInTimeRecovery(table),
"/ContinuousBackupsDescription/PointInTimeRecoveryDescription/EarliestRestorableDateTime");
expectError(exportAt(table, "export-checks", BigDecimal.valueOf(beforeCreate - 1000, 3)),
"InvalidExportTimeException", "Export Time is invalid");
expectError(exportAt(table, "export-checks", earliest.subtract(new BigDecimal("0.001"))),
"InvalidExportTimeException", "Point in Time Recovery is not available for specified export time");
expectError(exportAt(table, "export-checks", future), "InvalidExportTimeException", "Export Time is invalid");
exportAt(table, "export-checks", earliest).statusCode(200);
}
@Test
void exportTimeBeyondTheMillisecondRangeIsInvalid() {
String table = "ExportTimeRange";
createHashTable(table);
enablePointInTimeRecovery(table);
BigDecimal nowPlusTwoToThe64Millis = BigDecimal.valueOf(System.currentTimeMillis(), 3)
.add(new BigDecimal(BigInteger.TWO.pow(64), 3));
expectError(exportAt(table, "export-range", nowPlusTwoToThe64Millis),
"InvalidExportTimeException", "Export Time is invalid");
expectError(ddb("ExportTableToPointInTime", """
{"TableArn": "%s", "S3Bucket": "%s", "ExportTime": 1e400}
""".formatted(TABLE_ARN_PREFIX + table, BUCKET_NAME)),
"InvalidExportTimeException", "Export Time is invalid");
}
// --- Helpers ---
/** Returns a time between the writes before and after the call, in epoch seconds with milliseconds. */
private static BigDecimal pause() {
long now = System.currentTimeMillis();
while (System.currentTimeMillis() <= now) {
Thread.onSpinWait();
}
return BigDecimal.valueOf(now, 3);
}
private static void createHashTable(String table) {
ddb("CreateTable", """
{"TableName": "%s", "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
"AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}],
"BillingMode": "PAY_PER_REQUEST"}
""".formatted(table)).statusCode(200);
}
private static void putHashItem(String table, String pk, String value) {
ddb("PutItem", """
{"TableName": "%s", "Item": {"pk": {"S": "%s"}, "v": {"S": "%s"}}}
""".formatted(table, pk, value)).statusCode(200);
}
private static ValidatableResponse exportAt(String table, String prefix, BigDecimal exportTime) {
return ddb("ExportTableToPointInTime", """
{"TableArn": "%s", "S3Bucket": "%s", "S3Prefix": "%s", "ExportTime": %s}
""".formatted(TABLE_ARN_PREFIX + table, BUCKET_NAME, prefix, exportTime.toPlainString()));
}
private List<String> exportedItems(String exportArn, String prefix) throws Exception {
String exportId = exportArn.substring(exportArn.lastIndexOf('/') + 1);
String dataKey = given()
.when().get("/" + BUCKET_NAME + "/" + prefix + "/AWSDynamoDB/" + exportId + "/manifest-files.json")
.then().statusCode(200)
.extract().asString().trim();
byte[] gzipData = given()
.when().get("/" + BUCKET_NAME + "/" + dataKey)
.then().statusCode(200)
.extract().asByteArray();
List<String> items = new ArrayList<>();
for (String line : decompressGzip(gzipData).split("\n")) {
JsonPath item = JsonPath.from(line);
items.add(item.getString("Item.pk.S") + "=" + item.getString("Item.v.S"));
}
return items.stream().sorted().toList();
}
private static void expectError(ValidatableResponse response, String type, String message) {
response.statusCode(400)
.body("__type", containsString(type))
.body("message", equalTo(message));
}
private static ValidatableResponse enablePointInTimeRecovery(String table) {
return ddb("UpdateContinuousBackups", """
{"TableName": "%s", "PointInTimeRecoverySpecification": {"PointInTimeRecoveryEnabled": true}}
""".formatted(table)).statusCode(200);
}
private void putItem(String itemJson) {
given()
.header("X-Amz-Target", "DynamoDB_20120810.PutItem")
@@ -109,6 +109,9 @@ class DynamoDbImportIntegrationTest {
@Test
void importTable_gzip_roundTripsAnExport() {
createCompositeTable("RoundTripSource");
dynamo("UpdateContinuousBackups", """
{"TableName": "RoundTripSource", "PointInTimeRecoverySpecification": {"PointInTimeRecoveryEnabled": true}}
""").then().statusCode(200);
for (int i = 1; i <= 3; i++) {
dynamo("PutItem", "{\"TableName\": \"RoundTripSource\", \"Item\": {\"pk\": {\"S\": \"user-" + i
+ "\"}, \"sk\": {\"S\": \"order-" + i + "\"}, \"total\": {\"N\": \"" + (i * 10) + "\"}}}")
@@ -7,6 +7,7 @@ import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
@@ -186,6 +187,22 @@ class DynamoDbPointInTimeRecoveryIntegrationTest {
restoreToTime(table, "PitrIT-window-checks-earliest", earliest).statusCode(200);
}
@Test
void restoreDateTimeIsRoundedToTheMillisecondAsADouble() {
String table = "PitrIT-rounding";
createTable(table);
updateContinuousBackups(table, "true").statusCode(200);
String nowPlusTwoToThe64Millis = BigDecimal.valueOf(System.currentTimeMillis(), 3)
.add(new BigDecimal(BigInteger.TWO.pow(64), 3)).toPlainString();
assertEquals("+292278994-08-17T07:12:55.807Z", refusedRestoreTime(table, nowPlusTwoToThe64Millis));
assertEquals("+292278994-08-17T07:12:55.807Z", refusedRestoreTime(table, "1e400"));
assertEquals("-292275055-05-16T16:47:04.192Z", refusedRestoreTime(table, "-1e20"));
assertEquals("1970-01-01T00:00:00.001Z", refusedRestoreTime(table, "0.0005"));
assertEquals("1970-01-01T00:00:00Z", refusedRestoreTime(table, "-0.0005"));
assertEquals("2026-10-22T00:42:24.001Z", refusedRestoreTime(table, "1792629744.0004999"));
}
@Test
void restoreTableToPointInTimeChecksInTheAwsOrder() {
String table = "PitrIT-checks";
@@ -425,6 +442,16 @@ class DynamoDbPointInTimeRecoveryIntegrationTest {
return ddb("RestoreTableToPointInTime", "{" + members + "}");
}
private String refusedRestoreTime(String source, String restoreDateTime) {
String message = restore("""
"SourceTableName": "%s", "TargetTableName": "PitrIT-never", "RestoreDateTime": %s
""".formatted(source, restoreDateTime))
.statusCode(400)
.body("__type", containsString("InvalidRestoreTimeException"))
.extract().path("message");
return message.substring("RestoreDateTime '".length(), message.indexOf("' must be within"));
}
private static void expectError(ValidatableResponse response, String type, String message) {
response.statusCode(400)
.body("__type", containsString(type))
@@ -4493,6 +4493,19 @@ class DynamoDbServiceTest {
assertEquals("ResourceInUseException", e.getErrorCode());
}
@Test
void exportTable_whileCreating_returnsTableNotFoundException() {
createUsersTableInCreating(service);
String tableArn = "arn:aws:dynamodb:us-east-1:000000000000:table/Users";
Map<String, Object> request = Map.of("TableArn", tableArn, "S3Bucket", "bucket");
AwsException e = assertThrows(AwsException.class,
() -> service.exportTable(request, Instant.EPOCH, "us-east-1"));
assertEquals("TableNotFoundException", e.getErrorCode());
assertEquals("Table not found: " + tableArn, e.getMessage());
}
@Test
void validateImportRequest_rejectsUnsupportedFormatWithoutUnsupportedOperationWording() {
AwsException e = assertThrows(AwsException.class,