feat(dynamodb): import tables from S3 and report new exports as IN_PROGRESS (#3138)

* feat(dynamodb): import tables from S3 and report new exports as IN_PROGRESS

ExportTableToPointInTime handed its worker the same description object it
returned, so a small export could already read COMPLETED in the initial
response. The worker now mutates a copy and runs under the request account.

ImportTable creates the table in CREATING, loads DynamoDB JSON lines from
every object under the S3 prefix on a virtual thread, and flips the table
to ACTIVE when done. DescribeImport and ListImports report it. DYNAMODB_JSON
with NONE or GZIP compression is accepted. CSV, ION and ZSTD are rejected
with a ValidationException.

* fix(dynamodb): item calls on a CREATING table return ResourceNotFoundException

* fix(dynamodb): concurrent ImportTable calls with one ClientToken share one import

* fix(dynamodb): import reads S3 as the caller and denies another account's bucket
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-09-07 22:25:24 -05:00
1 parent fd21ac9a6d
commit cbec02df04
13 files changed
+1691 -55

No files matched your search

@@ -69,7 +69,7 @@ class DynamoDbExportIntegrationTest {
}
@Test
void exportTableToPointInTime_returnsInProgressOrCompleted() {
void exportTableToPointInTime_returnsInProgress() {
String exportArn = given()
.header("X-Amz-Target", "DynamoDB_20120810.ExportTableToPointInTime")
.contentType(DYNAMODB_CONTENT_TYPE)
@@ -85,7 +85,7 @@ class DynamoDbExportIntegrationTest {
.then()
.statusCode(200)
.body("ExportDescription.ExportArn", notNullValue())
.body("ExportDescription.ExportStatus", oneOf("IN_PROGRESS", "COMPLETED"))
.body("ExportDescription.ExportStatus", equalTo("IN_PROGRESS"))
.body("ExportDescription.TableArn", equalTo(TABLE_ARN))
.body("ExportDescription.S3Bucket", equalTo(BUCKET_NAME))
.body("ExportDescription.ExportFormat", equalTo("DYNAMODB_JSON"))
@@ -0,0 +1,462 @@
package io.github.hectorvent.floci.services.dynamodb;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.*;
@QuarkusTest
class DynamoDbImportIntegrationTest {
private static final String DYNAMODB_CONTENT_TYPE = "application/x-amz-json-1.0";
private static final String BUCKET_NAME = "import-test-bucket";
private static final String TABLE_ARN_PREFIX = "arn:aws:dynamodb:us-east-1:000000000000:table/";
private static boolean setupDone = false;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@BeforeEach
void ensureSetup() {
if (setupDone) {
return;
}
given()
.when().put("/" + BUCKET_NAME)
.then().statusCode(anyOf(equalTo(200), equalTo(409)));
setupDone = true;
}
@Test
void importTable_loadsNdjsonIntoNewTable() {
putObject("plain/data.json",
"{\"Item\":{\"pk\":{\"S\":\"imported1\"}}}\n{\"Item\":{\"pk\":{\"S\":\"imported2\"}}}\n");
var importArn = dynamo("ImportTable", importRequest("ImportPlain", BUCKET_NAME, "plain/", "DYNAMODB_JSON", "NONE"))
.then()
.statusCode(200)
.body("ImportTableDescription.ImportArn", containsString("/import/"))
.body("ImportTableDescription.ImportStatus", equalTo("IN_PROGRESS"))
.body("ImportTableDescription.TableArn", equalTo(TABLE_ARN_PREFIX + "ImportPlain"))
.body("ImportTableDescription.TableId", notNullValue())
.body("ImportTableDescription.S3BucketSource.S3Bucket", equalTo(BUCKET_NAME))
.body("ImportTableDescription.S3BucketSource.S3KeyPrefix", equalTo("plain/"))
.body("ImportTableDescription.InputFormat", equalTo("DYNAMODB_JSON"))
.body("ImportTableDescription.InputCompressionType", equalTo("NONE"))
.body("ImportTableDescription.TableCreationParameters.TableName", equalTo("ImportPlain"))
.body("ImportTableDescription.StartTime", notNullValue())
.extract().jsonPath().getString("ImportTableDescription.ImportArn");
dynamo("ListImports", "{}")
.then()
.statusCode(200)
.body("ImportSummaryList.ImportArn", hasItem(importArn));
dynamo("ListImports", "{\"TableArn\": \"" + TABLE_ARN_PREFIX + "ImportPlain\"}")
.then()
.statusCode(200)
.body("ImportSummaryList.ImportArn", hasItem(importArn))
.body("ImportSummaryList.find { it.ImportArn == '" + importArn + "' }.InputFormat", equalTo("DYNAMODB_JSON"));
dynamo("ListImports", "{\"TableArn\": \"" + TABLE_ARN_PREFIX + "SomeOtherTable\"}")
.then()
.statusCode(200)
.body("ImportSummaryList.ImportArn", not(hasItem(importArn)));
assertEquals("COMPLETED", pollUntilDone(importArn));
describeImport(importArn)
.then()
.statusCode(200)
.body("ImportTableDescription.ImportArn", equalTo(importArn))
.body("ImportTableDescription.ImportStatus", equalTo("COMPLETED"))
.body("ImportTableDescription.ProcessedItemCount", equalTo(2))
.body("ImportTableDescription.ImportedItemCount", equalTo(2))
.body("ImportTableDescription.ErrorCount", equalTo(0))
.body("ImportTableDescription.ProcessedSizeBytes", greaterThan(0))
.body("ImportTableDescription.EndTime", notNullValue());
dynamo("DescribeTable", "{\"TableName\": \"ImportPlain\"}")
.then()
.statusCode(200)
.body("Table.TableStatus", equalTo("ACTIVE"))
.body("Table.ItemCount", equalTo(2));
dynamo("GetItem", "{\"TableName\": \"ImportPlain\", \"Key\": {\"pk\": {\"S\": \"imported1\"}}}")
.then()
.statusCode(200)
.body("Item.pk.S", equalTo("imported1"));
}
@Test
void importTable_gzip_roundTripsAnExport() {
createCompositeTable("RoundTripSource");
for (var i = 1; i <= 3; i++) {
dynamo("PutItem", "{\"TableName\": \"RoundTripSource\", \"Item\": {\"pk\": {\"S\": \"user-" + i
+ "\"}, \"sk\": {\"S\": \"order-" + i + "\"}, \"total\": {\"N\": \"" + (i * 10) + "\"}}}")
.then().statusCode(200);
}
var exportArn = dynamo("ExportTableToPointInTime", """
{
"TableArn": "%s",
"S3Bucket": "%s",
"S3Prefix": "roundtrip"
}
""".formatted(TABLE_ARN_PREFIX + "RoundTripSource", BUCKET_NAME))
.then().statusCode(200)
.extract().jsonPath().getString("ExportDescription.ExportArn");
assertEquals("COMPLETED", pollExport(exportArn));
var exportId = exportArn.substring(exportArn.lastIndexOf('/') + 1);
var dataPrefix = "roundtrip/AWSDynamoDB/" + exportId + "/data/";
var importArn = dynamo("ImportTable", """
{
"S3BucketSource": {"S3Bucket": "%s", "S3KeyPrefix": "%s"},
"InputFormat": "DYNAMODB_JSON",
"InputCompressionType": "GZIP",
"TableCreationParameters": {
"TableName": "RoundTripTarget",
"AttributeDefinitions": [
{"AttributeName": "pk", "AttributeType": "S"},
{"AttributeName": "sk", "AttributeType": "S"}
],
"KeySchema": [
{"AttributeName": "pk", "KeyType": "HASH"},
{"AttributeName": "sk", "KeyType": "RANGE"}
],
"BillingMode": "PAY_PER_REQUEST"
}
}
""".formatted(BUCKET_NAME, dataPrefix))
.then().statusCode(200)
.body("ImportTableDescription.ImportStatus", equalTo("IN_PROGRESS"))
.extract().jsonPath().getString("ImportTableDescription.ImportArn");
assertEquals("COMPLETED", pollUntilDone(importArn));
describeImport(importArn)
.then()
.statusCode(200)
.body("ImportTableDescription.ImportedItemCount", equalTo(3))
.body("ImportTableDescription.ErrorCount", equalTo(0));
dynamo("Scan", "{\"TableName\": \"RoundTripTarget\"}")
.then()
.statusCode(200)
.body("Count", equalTo(3))
.body("Items.total.N", containsInAnyOrder("10", "20", "30"));
}
@Test
void importTable_skipsMalformedLinesAndCountsThem() {
putObject("bad/data.json",
"{\"Item\":{\"pk\":{\"S\":\"good\"}}}\nnot json at all\n{\"NoItem\":1}\n\n{\"Item\":{\"other\":{\"S\":\"missing key\"}}}\n");
var importArn = dynamo("ImportTable", importRequest("ImportBadLines", BUCKET_NAME, "bad/", "DYNAMODB_JSON", "NONE"))
.then().statusCode(200)
.extract().jsonPath().getString("ImportTableDescription.ImportArn");
assertEquals("COMPLETED", pollUntilDone(importArn));
describeImport(importArn)
.then()
.statusCode(200)
.body("ImportTableDescription.ProcessedItemCount", equalTo(4))
.body("ImportTableDescription.ImportedItemCount", equalTo(1))
.body("ImportTableDescription.ErrorCount", equalTo(3));
}
@Test
void importTable_missingBucket_failsWithS3NoSuchBucket() {
var importArn = dynamo("ImportTable", importRequest("ImportNoBucket", "no-such-import-bucket", "imp/", "DYNAMODB_JSON", "NONE"))
.then().statusCode(200)
.body("ImportTableDescription.ImportStatus", equalTo("IN_PROGRESS"))
.extract().jsonPath().getString("ImportTableDescription.ImportArn");
assertEquals("FAILED", pollUntilDone(importArn));
describeImport(importArn)
.then()
.statusCode(200)
.body("ImportTableDescription.FailureCode", equalTo("S3NoSuchBucket"))
.body("ImportTableDescription.FailureMessage", containsString("no-such-import-bucket"))
.body("ImportTableDescription.EndTime", notNullValue());
dynamo("DescribeTable", "{\"TableName\": \"ImportNoBucket\"}")
.then()
.statusCode(200)
.body("Table.TableStatus", equalTo("ACTIVE"))
.body("Table.ItemCount", equalTo(0));
}
@Test
void importTable_bucketOfAnotherAccount_failsWithS3AccessDenied() {
var importArn = dynamo("ImportTable", """
{
"S3BucketSource": {"S3Bucket": "%s", "S3KeyPrefix": "plain/", "S3BucketOwner": "111111111111"},
"InputFormat": "DYNAMODB_JSON",
"TableCreationParameters": {
"TableName": "ImportForeignBucket",
"AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}],
"KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
"BillingMode": "PAY_PER_REQUEST"
}
}
""".formatted(BUCKET_NAME))
.then().statusCode(200)
.body("ImportTableDescription.S3BucketSource.S3BucketOwner", equalTo("111111111111"))
.extract().jsonPath().getString("ImportTableDescription.ImportArn");
assertEquals("FAILED", pollUntilDone(importArn));
describeImport(importArn)
.then()
.statusCode(200)
.body("ImportTableDescription.FailureCode", equalTo("S3AccessDenied"))
.body("ImportTableDescription.FailureMessage", startsWith("Access Denied"))
.body("ImportTableDescription.ProcessedItemCount", equalTo(0));
}
@Test
void importTable_emptyPrefix_fails() {
var importArn = dynamo("ImportTable", importRequest("ImportEmptyPrefix", BUCKET_NAME, "nothing-here/", "DYNAMODB_JSON", "NONE"))
.then().statusCode(200)
.extract().jsonPath().getString("ImportTableDescription.ImportArn");
assertEquals("FAILED", pollUntilDone(importArn));
describeImport(importArn)
.then()
.statusCode(200)
.body("ImportTableDescription.FailureCode", equalTo("S3NoSuchKey"));
}
@Test
void importTable_sameClientToken_returnsTheSameImport() {
putObject("token/data.json", "{\"Item\":{\"pk\":{\"S\":\"one\"}}}\n");
var body = """
{
"ClientToken": "import-token-1",
"S3BucketSource": {"S3Bucket": "%s", "S3KeyPrefix": "token/"},
"InputFormat": "DYNAMODB_JSON",
"TableCreationParameters": {
"TableName": "ImportToken",
"AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}],
"KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
"BillingMode": "PAY_PER_REQUEST"
}
}
""".formatted(BUCKET_NAME);
var first = dynamo("ImportTable", body)
.then().statusCode(200)
.body("ImportTableDescription.ClientToken", equalTo("import-token-1"))
.extract().jsonPath().getString("ImportTableDescription.ImportArn");
var second = dynamo("ImportTable", body)
.then().statusCode(200)
.extract().jsonPath().getString("ImportTableDescription.ImportArn");
assertEquals(first, second);
}
/** Real DynamoDB hands identical concurrent requests the same ImportArn. */
@Test
void importTable_concurrentSameClientToken_startsOneImport() throws Exception {
putObject("race/data.json", "{\"Item\":{\"pk\":{\"S\":\"one\"}}}\n");
var body = """
{
"ClientToken": "import-token-race",
"S3BucketSource": {"S3Bucket": "%s", "S3KeyPrefix": "race/"},
"InputFormat": "DYNAMODB_JSON",
"TableCreationParameters": {
"TableName": "ImportRace",
"AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}],
"KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
"BillingMode": "PAY_PER_REQUEST"
}
}
""".formatted(BUCKET_NAME);
var threads = 8;
var startGate = new CountDownLatch(1);
var pool = Executors.newFixedThreadPool(threads);
try {
var futures = new ArrayList<Future<String>>();
for (var i = 0; i < threads; i++) {
futures.add(pool.submit(() -> {
startGate.await();
return dynamo("ImportTable", body)
.then().statusCode(200)
.extract().jsonPath().getString("ImportTableDescription.ImportArn");
}));
}
startGate.countDown();
var importArns = new HashSet<String>();
for (var future : futures) {
importArns.add(future.get(30, TimeUnit.SECONDS));
}
assertEquals(1, importArns.size(), importArns.toString());
} finally {
pool.shutdownNow();
}
dynamo("ListImports", "{\"TableArn\": \"" + TABLE_ARN_PREFIX + "ImportRace\"}")
.then()
.statusCode(200)
.body("ImportSummaryList", hasSize(1));
}
@Test
void importTable_existingTable_returnsResourceInUseException() {
createCompositeTable("ImportExisting");
dynamo("ImportTable", importRequest("ImportExisting", BUCKET_NAME, "plain/", "DYNAMODB_JSON", "NONE"))
.then()
.statusCode(400)
.body("__type", containsString("ResourceInUseException"))
.body("message", containsString("ImportExisting"));
}
@Test
void importTable_csvFormat_returnsValidationException() {
dynamo("ImportTable", importRequest("ImportCsv", BUCKET_NAME, "plain/", "CSV", "NONE"))
.then()
.statusCode(400)
.body("__type", containsString("ValidationException"))
.body("message", containsString("CSV"));
dynamo("DescribeTable", "{\"TableName\": \"ImportCsv\"}")
.then()
.statusCode(400)
.body("__type", containsString("ResourceNotFoundException"));
}
@Test
void importTable_zstdCompression_returnsValidationException() {
dynamo("ImportTable", importRequest("ImportZstd", BUCKET_NAME, "plain/", "DYNAMODB_JSON", "ZSTD"))
.then()
.statusCode(400)
.body("__type", containsString("ValidationException"))
.body("message", containsString("ZSTD"));
}
@Test
void importTable_missingBucketName_returnsValidationException() {
dynamo("ImportTable", "{\"InputFormat\": \"DYNAMODB_JSON\", \"TableCreationParameters\": {\"TableName\": \"ImportNoSource\"}}")
.then()
.statusCode(400)
.body("__type", containsString("ValidationException"));
}
@Test
void describeImport_notFound_returnsImportNotFoundException() {
describeImport(TABLE_ARN_PREFIX + "T/import/doesnotexist")
.then()
.statusCode(400)
.body("__type", containsString("ImportNotFoundException"));
}
// --- Helpers ---
private io.restassured.response.Response dynamo(String action, String body) {
return given()
.header("X-Amz-Target", "DynamoDB_20120810." + action)
.contentType(DYNAMODB_CONTENT_TYPE)
.body(body)
.when().post("/");
}
private void putObject(String key, String body) {
given()
.header("Content-Type", "application/octet-stream")
.body(body.getBytes(StandardCharsets.UTF_8))
.when().put("/" + BUCKET_NAME + "/" + key)
.then().statusCode(200);
}
private void createCompositeTable(String tableName) {
dynamo("CreateTable", """
{
"TableName": "%s",
"KeySchema": [
{"AttributeName": "pk", "KeyType": "HASH"},
{"AttributeName": "sk", "KeyType": "RANGE"}
],
"AttributeDefinitions": [
{"AttributeName": "pk", "AttributeType": "S"},
{"AttributeName": "sk", "AttributeType": "S"}
],
"BillingMode": "PAY_PER_REQUEST"
}
""".formatted(tableName))
.then().statusCode(200);
}
private String importRequest(String tableName, String bucket, String prefix, String format, String compression) {
return """
{
"S3BucketSource": {"S3Bucket": "%s", "S3KeyPrefix": "%s"},
"InputFormat": "%s",
"InputCompressionType": "%s",
"TableCreationParameters": {
"TableName": "%s",
"AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}],
"KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
"BillingMode": "PAY_PER_REQUEST"
}
}
""".formatted(bucket, prefix, format, compression, tableName);
}
private io.restassured.response.Response describeImport(String importArn) {
return dynamo("DescribeImport", "{\"ImportArn\": \"" + importArn + "\"}");
}
private String pollUntilDone(String importArn) {
return pollStatus(() -> describeImport(importArn), "ImportTableDescription.ImportStatus");
}
private String pollExport(String exportArn) {
return pollStatus(() -> dynamo("DescribeExport", "{\"ExportArn\": \"" + exportArn + "\"}"),
"ExportDescription.ExportStatus");
}
private String pollStatus(Supplier<io.restassured.response.Response> call, String statusPath) {
var deadline = System.currentTimeMillis() + 10_000;
while (System.currentTimeMillis() < deadline) {
var status = call.get().then().statusCode(200).extract().jsonPath().getString(statusPath);
if (!"IN_PROGRESS".equals(status)) {
return status;
}
sleep(100);
}
return "TIMEOUT";
}
private static void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
@@ -2,26 +2,35 @@ package io.github.hectorvent.floci.services.dynamodb;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition;
import io.github.hectorvent.floci.services.dynamodb.model.ConditionalCheckFailedException;
import io.github.hectorvent.floci.services.dynamodb.model.ExportDescription;
import io.github.hectorvent.floci.services.dynamodb.model.GlobalSecondaryIndex;
import io.github.hectorvent.floci.services.dynamodb.model.ImportTableDescription;
import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
import io.github.hectorvent.floci.services.dynamodb.model.LocalSecondaryIndex;
import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.GZIPOutputStream;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
@@ -31,6 +40,7 @@ import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
class DynamoDbServiceTest {
@@ -3754,4 +3764,353 @@ class DynamoDbServiceTest {
.put(any(), any());
assertNull(serviceWithMock.getItem("Users", item("userId", "u1"), "us-east-1"));
}
// --- ImportTable ---
private DynamoDbService serviceWithS3(S3Service s3, StorageBackend<String, ImportTableDescription> importStore) {
return new DynamoDbService(new InMemoryStorage<>(), new InMemoryStorage<>(), null, importStore,
new RegionResolver("us-east-1", "000000000000"), null, null, s3, mapper);
}
private void createUsersTableInCreating(DynamoDbService svc) {
svc.createTable("Users",
List.of(new KeySchemaElement("userId", "HASH")),
List.of(new AttributeDefinition("userId", "S")),
5L, 5L, "us-east-1").setTableStatus("CREATING");
}
private ImportTableDescription importDescription(String bucket, String prefix, String compression) {
var desc = new ImportTableDescription();
desc.setImportArn("arn:aws:dynamodb:us-east-1:000000000000:table/Users/import/1-abc");
var source = mapper.createObjectNode();
source.put("S3Bucket", bucket);
source.put("S3KeyPrefix", prefix);
desc.setS3BucketSource(source);
desc.setInputCompressionType(compression);
return desc;
}
private ObjectNode importRequest(String tableName, String inputFormat) {
var request = mapper.createObjectNode();
request.putObject("S3BucketSource").put("S3Bucket", "bucket").put("S3KeyPrefix", "imp/");
request.put("InputFormat", inputFormat);
request.putObject("TableCreationParameters").put("TableName", tableName);
return request;
}
private static byte[] gzip(String text) throws Exception {
var out = new ByteArrayOutputStream();
try (var gz = new GZIPOutputStream(out)) {
gz.write(text.getBytes(StandardCharsets.UTF_8));
}
return out.toByteArray();
}
private static S3Object s3Object(String key, byte[] data) {
return new S3Object("bucket", key, data, "application/octet-stream");
}
private static S3Service s3With(S3Object... objects) {
var s3 = mock(S3Service.class);
when(s3.listObjects("bucket", "imp/", null, 0)).thenReturn(List.of(objects));
for (var object : objects) {
when(s3.getObjectMetadata("bucket", object.getKey(), null)).thenReturn(object);
when(s3.openObjectStream("bucket", object.getKey(), null))
.thenAnswer(invocation -> new ByteArrayInputStream(object.getData()));
}
return s3;
}
/** Checked against real DynamoDB: every item call on a CREATING table fails this way, DescribeTable still works. */
@Test
void itemCalls_creatingTable_returnResourceNotFoundWithoutTableName() {
var svc = serviceWithS3(mock(S3Service.class), new InMemoryStorage<>());
createUsersTableInCreating(svc);
var region = "us-east-1";
var key = item("userId", "u1");
var keys = mapper.createObjectNode();
keys.set("Keys", mapper.createArrayNode().add(key));
var putRequest = mapper.createObjectNode();
putRequest.putObject("PutRequest").set("Item", key);
var transactPut = mapper.createObjectNode();
transactPut.putObject("Put").put("TableName", "Users").set("Item", key);
var transactGet = mapper.createObjectNode();
transactGet.putObject("Get").put("TableName", "Users").set("Key", key);
List<org.junit.jupiter.api.function.Executable> itemCalls = List.of(
() -> svc.getItem("Users", key, region),
() -> svc.putItem("Users", key, null, null, null, region, "NONE"),
() -> svc.updateItem("Users", key, null, "SET x = :v", null, item("v", "1"), "NONE", region),
() -> svc.deleteItem("Users", key, region),
() -> svc.query("Users", null, item("pk", "u1"), "userId = :pk", null, null, region),
() -> svc.scan("Users", null, null, null, null, null, null, null, region),
() -> svc.batchGetItem(Map.of("Users", keys), region),
() -> svc.batchWriteItem(Map.of("Users", List.of(putRequest)), region),
() -> svc.transactWriteItems(List.of(transactPut), region, null, null),
() -> svc.transactGetItems(List.of(transactGet), region));
for (var call : itemCalls) {
var e = assertThrows(AwsException.class, call);
assertEquals("ResourceNotFoundException", e.getErrorCode());
assertEquals("Requested resource not found", e.getMessage());
}
assertEquals("CREATING", svc.describeTable("Users", region).getTableStatus());
}
@Test
void runImport_loadsGzipLinesAndCountsBadOnes() throws Exception {
var object = s3Object("imp/part-0.json.gz",
gzip("{\"Item\":{\"userId\":{\"S\":\"u1\"}}}\nnot json\n{\"Item\":{\"userId\":{\"S\":\"u2\"}}}\n"));
var importStore = new InMemoryStorage<String, ImportTableDescription>();
var svc = serviceWithS3(s3With(object), importStore);
createUsersTableInCreating(svc);
var desc = importDescription("bucket", "imp/", "GZIP");
svc.runImport(desc, "Users", "us-east-1");
assertEquals("COMPLETED", desc.getImportStatus());
assertEquals(3L, desc.getProcessedItemCount());
assertEquals(2L, desc.getImportedItemCount());
assertEquals(1L, desc.getErrorCount());
assertTrue(desc.getProcessedSizeBytes() > 0);
assertNotNull(desc.getEndTime());
assertEquals("COMPLETED", importStore.get(desc.getImportArn()).orElseThrow().getImportStatus());
assertEquals("ACTIVE", svc.describeTable("Users", "us-east-1").getTableStatus());
assertEquals("u2", svc.getItem("Users", item("userId", "u2"), "us-east-1").get("userId").get("S").asText());
}
/** Checked against real DynamoDB: another account's bucket fails this way when no policy grants access. */
@Test
void runImport_bucketOfAnotherAccount_failsWithS3AccessDeniedWithoutReadingS3() {
var s3 = mock(S3Service.class);
var svc = serviceWithS3(s3, new InMemoryStorage<>());
createUsersTableInCreating(svc);
var desc = importDescription("bucket", "imp/", "NONE");
((ObjectNode) desc.getS3BucketSource()).put("S3BucketOwner", "111111111111");
svc.runImport(desc, "Users", "us-east-1");
assertEquals("FAILED", desc.getImportStatus());
assertEquals("S3AccessDenied", desc.getFailureCode());
assertEquals("Access Denied (Service: Amazon S3; Status Code: 403; Error Code: AccessDenied)", desc.getFailureMessage());
verifyNoInteractions(s3);
assertEquals("ACTIVE", svc.describeTable("Users", "us-east-1").getTableStatus());
}
@Test
void runImport_bucketOwnerIsTheCaller_readsTheBucket() {
var object = s3Object("imp/data.json", "{\"Item\":{\"userId\":{\"S\":\"u1\"}}}\n".getBytes(StandardCharsets.UTF_8));
var svc = serviceWithS3(s3With(object), new InMemoryStorage<>());
createUsersTableInCreating(svc);
var desc = importDescription("bucket", "imp/", "NONE");
((ObjectNode) desc.getS3BucketSource()).put("S3BucketOwner", "000000000000");
svc.runImport(desc, "Users", "us-east-1");
assertEquals("COMPLETED", desc.getImportStatus());
assertEquals(1L, desc.getImportedItemCount());
}
@Test
void runImport_persistsLoadedItems() {
var object = s3Object("imp/data.json",
"{\"Item\":{\"userId\":{\"S\":\"u1\"}}}\n{\"Item\":{\"userId\":{\"S\":\"u2\"}}}\n".getBytes(StandardCharsets.UTF_8));
var itemStore = new InMemoryStorage<String, Map<String, JsonNode>>();
var svc = new DynamoDbService(new InMemoryStorage<>(), itemStore, null, new InMemoryStorage<>(),
new RegionResolver("us-east-1", "000000000000"), null, null, s3With(object), mapper);
createUsersTableInCreating(svc);
svc.runImport(importDescription("bucket", "imp/", "NONE"), "Users", "us-east-1");
assertEquals(1, itemStore.scan(k -> true).size());
assertEquals(2, itemStore.scan(k -> true).getFirst().size());
}
@Test
void runImport_unreadableObject_isCountedAndTheRestIsLoaded() throws Exception {
var data = s3Object("imp/data.json.gz", gzip("{\"Item\":{\"userId\":{\"S\":\"u1\"}}}\n"));
var manifest = s3Object("imp/manifest-summary.json", "{}".getBytes(StandardCharsets.UTF_8));
var svc = serviceWithS3(s3With(data, manifest), new InMemoryStorage<>());
createUsersTableInCreating(svc);
var desc = importDescription("bucket", "imp/", "GZIP");
svc.runImport(desc, "Users", "us-east-1");
assertEquals("COMPLETED", desc.getImportStatus());
assertEquals(1L, desc.getImportedItemCount());
assertEquals(1L, desc.getErrorCount());
assertEquals("ACTIVE", svc.describeTable("Users", "us-east-1").getTableStatus());
}
@Test
void runImport_malformedAttributeValue_isCountedNotFatal() {
var object = s3Object("imp/data.json",
("{\"Item\":{\"userId\":{\"S\":\"u1\"},\"m\":{\"M\":\"not a map\"}}}\n"
+ "{\"Item\":{\"userId\":{\"S\":\"u2\"}}}\n").getBytes(StandardCharsets.UTF_8));
var svc = serviceWithS3(s3With(object), new InMemoryStorage<>());
createUsersTableInCreating(svc);
var desc = importDescription("bucket", "imp/", "NONE");
svc.runImport(desc, "Users", "us-east-1");
assertEquals("COMPLETED", desc.getImportStatus());
assertEquals(1L, desc.getImportedItemCount());
assertEquals(1L, desc.getErrorCount());
}
@Test
void runImport_missingBucket_failsWithS3NoSuchBucket() {
var s3 = mock(S3Service.class);
when(s3.listObjects("missing", "imp/", null, 0))
.thenThrow(new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404));
var svc = serviceWithS3(s3, new InMemoryStorage<>());
createUsersTableInCreating(svc);
var desc = importDescription("missing", "imp/", "NONE");
svc.runImport(desc, "Users", "us-east-1");
assertEquals("FAILED", desc.getImportStatus());
assertEquals("S3NoSuchBucket", desc.getFailureCode());
assertNotNull(desc.getEndTime());
assertEquals("ACTIVE", svc.describeTable("Users", "us-east-1").getTableStatus());
}
@Test
void runImport_otherS3Error_reportsAnS3FailureCode() {
var s3 = mock(S3Service.class);
when(s3.listObjects("bucket", "imp/", null, 0))
.thenThrow(new AwsException("AccessDenied", "Access Denied", 403));
var svc = serviceWithS3(s3, new InMemoryStorage<>());
createUsersTableInCreating(svc);
var desc = importDescription("bucket", "imp/", "NONE");
svc.runImport(desc, "Users", "us-east-1");
assertEquals("FAILED", desc.getImportStatus());
assertEquals("S3AccessDenied", desc.getFailureCode());
}
@Test
void deleteTable_whileCreating_returnsResourceInUseException() {
createUsersTableInCreating(service);
var e = assertThrows(AwsException.class, () -> service.deleteTable("Users", "us-east-1"));
assertEquals("ResourceInUseException", e.getErrorCode());
assertEquals("CREATING", service.describeTable("Users", "us-east-1").getTableStatus());
}
@Test
void updateTable_whileCreating_returnsResourceInUseException() {
createUsersTableInCreating(service);
var e = assertThrows(AwsException.class, () -> service.updateTable("Users", 10L, 10L, "us-east-1"));
assertEquals("ResourceInUseException", e.getErrorCode());
}
@Test
void validateImportRequest_rejectsUnsupportedFormatWithoutUnsupportedOperationWording() {
var e = assertThrows(AwsException.class,
() -> service.validateImportRequest(importRequest("Users", "CSV")));
assertEquals("ValidationException", e.getErrorCode());
assertTrue(e.getMessage().contains("CSV"));
assertFalse(e.getMessage().toLowerCase().contains("not supported"));
}
@Test
void validateImportRequest_blankClientToken_returnsValidationException() {
var request = importRequest("Users", "DYNAMODB_JSON");
request.put("ClientToken", "");
var e = assertThrows(AwsException.class, () -> service.validateImportRequest(request));
assertEquals("ValidationException", e.getErrorCode());
}
@Test
void validateImportRequest_sameClientToken_returnsExistingImport() {
var importStore = new InMemoryStorage<String, ImportTableDescription>();
var request = importRequest("Users", "DYNAMODB_JSON");
request.put("ClientToken", "token-1");
var existing = importDescription("bucket", "imp/", "NONE");
existing.setClientToken("token-1");
existing.setInputFormat("DYNAMODB_JSON");
existing.setTableCreationParameters(request.get("TableCreationParameters"));
importStore.put(existing.getImportArn(), existing);
var svc = serviceWithS3(mock(S3Service.class), importStore);
assertSame(existing, svc.validateImportRequest(request));
}
@Test
void validateImportRequest_sameClientTokenDifferentParameters_returnsImportConflictException() {
var importStore = new InMemoryStorage<String, ImportTableDescription>();
var existing = importDescription("bucket", "imp/", "NONE");
existing.setClientToken("token-1");
existing.setInputFormat("DYNAMODB_JSON");
existing.setTableCreationParameters(mapper.createObjectNode().put("TableName", "Users"));
importStore.put(existing.getImportArn(), existing);
var svc = serviceWithS3(mock(S3Service.class), importStore);
var request = importRequest("Other", "DYNAMODB_JSON");
request.put("ClientToken", "token-1");
var e = assertThrows(AwsException.class, () -> svc.validateImportRequest(request));
assertEquals("ImportConflictException", e.getErrorCode());
}
@Test
void listImports_pageSizeBelowOne_returnsValidationException() {
var svc = serviceWithS3(mock(S3Service.class), new InMemoryStorage<>());
var e = assertThrows(AwsException.class, () -> svc.listImports(null, 0, null));
assertEquals("ValidationException", e.getErrorCode());
}
@Test
void listImports_walksPagesByNextToken() {
var importStore = new InMemoryStorage<String, ImportTableDescription>();
for (var i = 1; i <= 3; i++) {
var desc = importDescription("bucket", "imp/", "NONE");
desc.setImportArn("arn:aws:dynamodb:us-east-1:000000000000:table/Users/import/" + i + "-abc");
importStore.put(desc.getImportArn(), desc);
}
var svc = serviceWithS3(mock(S3Service.class), importStore);
var first = svc.listImports(null, 2, null);
var second = svc.listImports(null, 2, first.nextToken());
assertEquals(2, first.importSummaryList().size());
assertNotNull(first.nextToken());
assertEquals(1, second.importSummaryList().size());
assertNull(second.nextToken());
}
@Test
void constructor_failsInterruptedJobsAndActivatesCreatingTables() {
var resolver = new RegionResolver("us-east-1", "000000000000");
var tables = new AccountAwareStorageBackend<TableDefinition>(new InMemoryStorage<>(), null, "000000000000");
var exports = new AccountAwareStorageBackend<ExportDescription>(new InMemoryStorage<>(), null, "000000000000");
var imports = new AccountAwareStorageBackend<ImportTableDescription>(new InMemoryStorage<>(), null, "000000000000");
var before = new DynamoDbService(tables, new InMemoryStorage<>(), exports, imports,
resolver, null, null, mock(S3Service.class), mapper);
createUsersTableInCreating(before);
var importDesc = importDescription("bucket", "imp/", "NONE");
importDesc.setImportStatus("IN_PROGRESS");
imports.put(importDesc.getImportArn(), importDesc);
var exportDesc = new ExportDescription();
exportDesc.setExportArn("arn:aws:dynamodb:us-east-1:000000000000:table/Users/export/1-abc");
exportDesc.setExportStatus("IN_PROGRESS");
exports.put(exportDesc.getExportArn(), exportDesc);
var restarted = new DynamoDbService(tables, new InMemoryStorage<>(), exports, imports,
resolver, null, null, mock(S3Service.class), mapper);
assertEquals("ACTIVE", restarted.describeTable("Users", "us-east-1").getTableStatus());
assertEquals("FAILED", restarted.describeImport(importDesc.getImportArn()).getImportStatus());
assertEquals("InterruptedByRestart", restarted.describeImport(importDesc.getImportArn()).getFailureCode());
assertEquals("FAILED", restarted.describeExport(exportDesc.getExportArn()).getExportStatus());
}
}
@@ -196,6 +196,13 @@ class ResourceArnBuilderTest {
), arns);
}
@Test
void dynamoDbBuildsArnFromTableCreationParameters() {
setJsonBody("{\"TableCreationParameters\":{\"TableName\":\"ImportTarget\"},\"InputFormat\":\"DYNAMODB_JSON\"}");
var arn = builder.build("dynamodb", ctx, "us-east-1", "000000000000");
assertEquals("arn:aws:dynamodb:us-east-1:000000000000:table/ImportTarget", arn);
}
@Test
void dynamoDbReturnsWildcardWhenNoTableSpecified() {
setJsonBody("{}");