mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(dynamodb): optional DynamoDB Local backend (#4504)
* feat(dynamodb): add the external Local operation client Adds DynamoDbLocalClient, which forwards DynamoDB and DynamoDB Streams wire calls to an external DynamoDB Local over SigV4-signed HTTP/1.1. The caller's account becomes the access key and its region the signing region, so Local keeps each account and region apart. Requests are never retried. Reply.successBody now owns the AWS error body conversion, which the API stream reader reuses. * feat(dynamodb): add the DynamoDB Local backend Adds DynamoDbLocalBackend, a DynamoDbBackend that forwards every wire call to an external DynamoDB Local through DynamoDbLocalClient. - Namespaces: the caller's account and region select the Local namespace; table and stream ARNs from another account or region are rejected. - Identities: table, index and stream ARNs in replies are rewritten from Local's fixed ddblocal shape to public ARNs, and stream records carry the caller's region. - Metadata: tags live in a Floci store because Local keeps none; replica updates are refused; a global table is its single-region table; stream enable and disable are idempotent like native. - Lifecycle: startup waits up to 30s for Local to accept connections, and emulator resets are refused because the data lives outside Floci. DynamoDbBackend groups the four seam interfaces so one object is the whole engine. * feat(dynamodb): enable the optional Local backend floci.services.dynamodb.backend selects the engine: native (default) or local, which forwards to the DynamoDB Local at local-endpoint. Both engines are client proxies, so the unselected one is never constructed. With local selected, the stream reader keeps checkpoints for the life of the stream, and /_floci/info reports the backend in dynamodb_backend. DynamoDbLocalBackendIntegrationTest runs against a real DynamoDB Local when FLOCI_SERVICES_DYNAMODB_LOCAL_ENDPOINT is set. * docs(dynamodb): document the DynamoDB Local backend * fix(dynamodb): harden the Local backend endpoint check, stream paging and startup probe Reject AWS endpoints in every partition, with a trailing dot, and endpoints with user info. Translate ListStreams paging ARNs, retry any I/O failure until the startup deadline, and call DescribeTable outside the tag lock. * fix(dynamodb): tighten Local ARN ownership, batch table names and global TableId A table ARN of another account or partition is ResourceNotFoundException, a stream ARN of another partition is refused, and a batch naming one table twice is a ValidationException instead of a dropped entry. A global table on Local has an empty TableId instead of a random one. Document the Resource Explorer limit. * fix(dynamodb): mark the Local readiness probe region as partition-invariant * test(dynamodb): pin the table record of an untagged typed Local create * docs(dynamodb): state the Local readiness bound and stack delete protection * fix(dynamodb): lift deletion protection on the Local direct delete and cap the readiness probe - DynamoDbTableAccess.deleteTable is the direct engine delete with no deletion-protection check. The Local backend now clears DeletionProtectionEnabled before DeleteTable, so CloudFormation deletes behave the same on both backends. The wire DeleteTable still enforces it. - Each readiness probe is bounded by the remaining 30 second budget and never exceeds the configured request timeout, so startup fails within the budget. * fix(dynamodb): align Local tag errors with the native wire path - ListTagsOfResource on a missing table is AccessDeniedException, as on the native wire path. - A table ARN whose partition is not an AWS partition is a ValidationException instead of a foreign resource. - Tag operations report a table ARN of another region as ResourceNotFoundException, as native does; TableName fields keep the region-mismatch ValidationException. - Document which regions Resource Explorer searches, and note that a failed direct delete leaves deletion protection off. * docs(dynamodb): state the tested DynamoDB Local version
This commit is contained in:
1 parent
833a43bfa7
commit
c326dce977
21 files changed
+2338
-32
No files matched your search
+2
-1
@@ -92,7 +92,8 @@ class EmulatorInfoControllerIntegrationTest {
|
||||
.statusCode(200)
|
||||
.contentType("application/json")
|
||||
.body("edition", equalTo("community"))
|
||||
.body("version", notNullValue());
|
||||
.body("version", notNullValue())
|
||||
.body("dynamodb_backend", equalTo("native"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
|
||||
@@ -6,6 +6,7 @@ import io.github.hectorvent.floci.core.common.ContainerTeardown;
|
||||
import io.github.hectorvent.floci.core.common.Resettable;
|
||||
import io.github.hectorvent.floci.core.common.ServiceRegistry;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbBackendSelector;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
@@ -16,6 +17,7 @@ import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
@@ -40,6 +42,7 @@ class EmulatorInfoControllerTest {
|
||||
@Mock private Instance<ContainerTeardown> containerTeardowns;
|
||||
@Mock private FlociCertificateAuthority certificateAuthority;
|
||||
@Mock private EmulatorConfig config;
|
||||
@Mock private DynamoDbBackendSelector dynamoDbBackendSelector;
|
||||
@Mock private ContainerTeardown sageMakerTeardown;
|
||||
@Mock private ContainerTeardown batchTeardown;
|
||||
@Mock private Resettable resettable;
|
||||
@@ -49,7 +52,17 @@ class EmulatorInfoControllerTest {
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
controller = new EmulatorInfoController(serviceRegistry, initLifecycleState, storageFactory,
|
||||
resettables, containerTeardowns, certificateAuthority, config);
|
||||
resettables, containerTeardowns, certificateAuthority, config, dynamoDbBackendSelector);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should report the selected DynamoDB backend in info")
|
||||
void info_reportsTheSelectedDynamoDbBackend() {
|
||||
when(dynamoDbBackendSelector.selected()).thenReturn("local");
|
||||
|
||||
Map<?, ?> info = (Map<?, ?>) controller.info().getEntity();
|
||||
|
||||
assertEquals("local", info.get("dynamodb_backend"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+1
-1
@@ -115,6 +115,6 @@ class CloudWatchLogsMetricFilterResetTest {
|
||||
when(resettables.iterator()).thenAnswer(call -> List.of(resettable).iterator());
|
||||
Instance<ContainerTeardown> teardowns = mock(Instance.class);
|
||||
when(teardowns.iterator()).thenAnswer(call -> List.<ContainerTeardown>of().iterator());
|
||||
return new EmulatorInfoController(null, null, f.factory, resettables, teardowns, null, null);
|
||||
return new EmulatorInfoController(null, null, f.factory, resettables, teardowns, null, null, null);
|
||||
}
|
||||
}
|
||||
+73
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.dynamodb.backend;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.resource.ResourceProvider;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade;
|
||||
@@ -18,8 +19,10 @@ import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbStreamReader
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
|
||||
import io.quarkus.arc.Arc;
|
||||
import io.quarkus.arc.ClientProxy;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -28,11 +31,16 @@ import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** The one DynamoDB backend CDI selects, and the one Resource Explorer provider in front of it. */
|
||||
@QuarkusTest
|
||||
@@ -64,16 +72,81 @@ class DynamoDbBackendSelectionTest {
|
||||
@Inject
|
||||
ObjectMapper mapper;
|
||||
|
||||
@Inject
|
||||
DynamoDbBackendSelector selector;
|
||||
|
||||
@Test
|
||||
void everyCapabilityIsTheOneNativeBackend() {
|
||||
Object backend = ClientProxy.unwrap(operations);
|
||||
|
||||
assertEquals("native", selector.selected());
|
||||
assertInstanceOf(NativeDynamoDbBackend.class, backend);
|
||||
assertSame(backend, ClientProxy.unwrap(items));
|
||||
assertSame(backend, ClientProxy.unwrap(tables));
|
||||
assertSame(backend, ClientProxy.unwrap(lifecycle));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theUnselectedLocalBackendIsNeverConstructed() {
|
||||
assertFalse(Arc.container().getActiveContext(ApplicationScoped.class).getState().getContextualInstances()
|
||||
.keySet().stream().anyMatch(bean -> bean.getBeanClass() == DynamoDbLocalBackend.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nativeServesEverySeamWithProcessCheckpoints() {
|
||||
NativeDynamoDbBackend nativeBackend = mock(NativeDynamoDbBackend.class);
|
||||
DynamoDbLocalBackend localBackend = mock(DynamoDbLocalBackend.class);
|
||||
DynamoDbBackendSelector nativeSelector = new DynamoDbBackendSelector(config("native"), nativeBackend, localBackend);
|
||||
|
||||
assertEquals("native", nativeSelector.selected());
|
||||
assertServesEverySeam(nativeBackend, nativeSelector);
|
||||
assertEquals(CheckpointLifetime.PROCESS, nativeSelector.streamReader().checkpointLifetime());
|
||||
verifyNoInteractions(localBackend);
|
||||
}
|
||||
|
||||
@Test
|
||||
void localServesEverySeamWithStreamCheckpoints() {
|
||||
NativeDynamoDbBackend nativeBackend = mock(NativeDynamoDbBackend.class);
|
||||
DynamoDbLocalBackend localBackend = mock(DynamoDbLocalBackend.class);
|
||||
DynamoDbBackendSelector localSelector = new DynamoDbBackendSelector(config("local"), nativeBackend, localBackend);
|
||||
|
||||
assertEquals("local", localSelector.selected());
|
||||
assertServesEverySeam(localBackend, localSelector);
|
||||
assertEquals(CheckpointLifetime.STREAM, localSelector.streamReader().checkpointLifetime());
|
||||
verifyNoInteractions(nativeBackend);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theBackendNameIsTrimmedAndCaseInsensitive() {
|
||||
DynamoDbLocalBackend localBackend = mock(DynamoDbLocalBackend.class);
|
||||
DynamoDbBackendSelector localSelector =
|
||||
new DynamoDbBackendSelector(config(" LOCAL "), mock(NativeDynamoDbBackend.class), localBackend);
|
||||
|
||||
assertEquals("local", localSelector.selected());
|
||||
assertSame(localBackend, localSelector.operations());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnknownBackendFailsSelection() {
|
||||
IllegalStateException failure = assertThrows(IllegalStateException.class, () -> new DynamoDbBackendSelector(
|
||||
config("sqlite"), mock(NativeDynamoDbBackend.class), mock(DynamoDbLocalBackend.class)));
|
||||
|
||||
assertEquals("floci.services.dynamodb.backend must be 'native' or 'local', got 'sqlite'", failure.getMessage());
|
||||
}
|
||||
|
||||
private static EmulatorConfig config(String backend) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.services().dynamodb().backend()).thenReturn(backend);
|
||||
return config;
|
||||
}
|
||||
|
||||
private static void assertServesEverySeam(DynamoDbBackend expected, DynamoDbBackendSelector selector) {
|
||||
assertSame(expected, selector.operations());
|
||||
assertSame(expected, selector.itemAccess());
|
||||
assertSame(expected, selector.tableAccess());
|
||||
assertSame(expected, selector.lifecycle());
|
||||
}
|
||||
|
||||
@Test
|
||||
void startupSchedulesTheTtlSweep() {
|
||||
assertTrue(Thread.getAllStackTraces().keySet().stream()
|
||||
|
||||
+302
@@ -0,0 +1,302 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb.backend;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Scope;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbStreamReader.CheckpointLifetime;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbStreamReader.Cursor;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbStreamReader.Position;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbStreamReader.RecordsPage;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbStreamReader.Shard;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbStreamReader.Stream;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.QuarkusTestProfile;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.contains;
|
||||
import static org.hamcrest.Matchers.containsInAnyOrder;
|
||||
import static org.hamcrest.Matchers.endsWith;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.hamcrest.Matchers.nullValue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/** The DynamoDB API served by an external DynamoDB Local, reached at FLOCI_SERVICES_DYNAMODB_LOCAL_ENDPOINT. */
|
||||
@QuarkusTest
|
||||
@TestProfile(DynamoDbLocalBackendIntegrationTest.LocalProfile.class)
|
||||
@EnabledIfEnvironmentVariable(named = DynamoDbLocalBackendIntegrationTest.ENDPOINT_VARIABLE, matches = ".+")
|
||||
class DynamoDbLocalBackendIntegrationTest {
|
||||
|
||||
static final String ENDPOINT_VARIABLE = "FLOCI_SERVICES_DYNAMODB_LOCAL_ENDPOINT";
|
||||
|
||||
public static final class LocalProfile implements QuarkusTestProfile {
|
||||
@Override
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
String endpoint = System.getenv(ENDPOINT_VARIABLE);
|
||||
return Map.of("floci.services.dynamodb.backend", "local",
|
||||
"floci.services.dynamodb.local-endpoint", endpoint == null ? "" : endpoint);
|
||||
}
|
||||
}
|
||||
|
||||
private record Caller(String account, String region) {
|
||||
String authorization() {
|
||||
return "AWS4-HMAC-SHA256 Credential=" + account + "/20260215/" + region
|
||||
+ "/dynamodb/aws4_request, SignedHeaders=host, Signature=abc";
|
||||
}
|
||||
}
|
||||
|
||||
private record CreatedTable(Caller caller, String name) {}
|
||||
|
||||
private static final String CONTENT_TYPE = "application/x-amz-json-1.0";
|
||||
private static final String ACCOUNT_A = randomAccount();
|
||||
private static final String ACCOUNT_B = otherAccountThan(ACCOUNT_A);
|
||||
private static final Caller A_EAST = new Caller(ACCOUNT_A, "us-east-1");
|
||||
private static final Caller A_WEST = new Caller(ACCOUNT_A, "eu-west-1");
|
||||
private static final Caller B_EAST = new Caller(ACCOUNT_B, "us-east-1");
|
||||
private static final String STREAMED = ", \"StreamSpecification\": {\"StreamEnabled\": true, "
|
||||
+ "\"StreamViewType\": \"NEW_AND_OLD_IMAGES\"}";
|
||||
|
||||
@Inject
|
||||
DynamoDbStreamReader streamReader;
|
||||
|
||||
@Inject
|
||||
DynamoDbFacade dynamoDbFacade;
|
||||
|
||||
private final List<CreatedTable> created = new ArrayList<>();
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void deleteCreatedTables() {
|
||||
for (CreatedTable table : created) {
|
||||
dynamoDb(table.caller(), "DeleteTable", "{\"TableName\": \"" + table.name() + "\"}").statusCode(200);
|
||||
}
|
||||
created.clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSameTableNameIsIsolatedAcrossAccountsAndRegions() {
|
||||
String table = tableName("isolation");
|
||||
for (Caller caller : List.of(A_EAST, B_EAST, A_WEST)) {
|
||||
createTable(caller, table, "").statusCode(200);
|
||||
}
|
||||
putItem(A_EAST, table, "only-in-a-east");
|
||||
|
||||
scanCount(A_EAST, table).body("Count", equalTo(1));
|
||||
scanCount(B_EAST, table).body("Count", equalTo(0));
|
||||
scanCount(A_WEST, table).body("Count", equalTo(0));
|
||||
dynamoDb(B_EAST, "GetItem", "{\"TableName\": \"" + table + "\", \"Key\": {\"pk\": {\"S\": \"only-in-a-east\"}}}")
|
||||
.statusCode(200)
|
||||
.body("Item", nullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tableArnsArePublicAndAcceptedAsTableNames() {
|
||||
String table = tableName("arn");
|
||||
String arn = tableArn(A_WEST, table);
|
||||
|
||||
createTable(A_WEST, table, "").statusCode(200).body("TableDescription.TableArn", equalTo(arn));
|
||||
|
||||
dynamoDb(A_WEST, "DescribeTable", "{\"TableName\": \"" + arn + "\"}")
|
||||
.statusCode(200)
|
||||
.body("Table.TableName", equalTo(table))
|
||||
.body("Table.TableArn", equalTo(arn));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagsRoundTripAlongsideCreateTableTags() {
|
||||
String table = tableName("tags");
|
||||
String arn = tableArn(B_EAST, table);
|
||||
createTable(B_EAST, table, ", \"Tags\": [{\"Key\": \"env\", \"Value\": \"test\"}]").statusCode(200);
|
||||
|
||||
dynamoDb(B_EAST, "TagResource",
|
||||
"{\"ResourceArn\": \"" + arn + "\", \"Tags\": [{\"Key\": \"team\", \"Value\": \"data\"}]}")
|
||||
.statusCode(200);
|
||||
dynamoDb(B_EAST, "ListTagsOfResource", "{\"ResourceArn\": \"" + arn + "\"}")
|
||||
.statusCode(200)
|
||||
.body("Tags.Key", containsInAnyOrder("env", "team"));
|
||||
|
||||
dynamoDb(B_EAST, "UntagResource", "{\"ResourceArn\": \"" + arn + "\", \"TagKeys\": [\"env\"]}")
|
||||
.statusCode(200);
|
||||
dynamoDb(B_EAST, "ListTagsOfResource", "{\"ResourceArn\": \"" + arn + "\"}")
|
||||
.statusCode(200)
|
||||
.body("Tags.Key", contains("team"))
|
||||
.body("Tags.Value", contains("data"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listingTagsOfAMissingTableIsAccessDenied() {
|
||||
dynamoDb(B_EAST, "ListTagsOfResource", "{\"ResourceArn\": \"" + tableArn(B_EAST, tableName("absent")) + "\"}")
|
||||
.statusCode(400)
|
||||
.body("__type", endsWith("AccessDeniedException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void streamRecordsCarryPublicArnsAndTheCallerRegion() {
|
||||
String table = tableName("stream");
|
||||
String streamArn = streamedTableWithOneItem(A_WEST, table);
|
||||
assertTrue(streamArn.startsWith(tableArn(A_WEST, table) + "/stream/"), streamArn);
|
||||
|
||||
streams(A_WEST, "ListStreams", "{\"TableName\": \"" + table + "\"}")
|
||||
.statusCode(200)
|
||||
.body("Streams.StreamArn", contains(streamArn));
|
||||
String shardId = streams(A_WEST, "DescribeStream", "{\"StreamArn\": \"" + streamArn + "\"}")
|
||||
.statusCode(200)
|
||||
.body("StreamDescription.StreamArn", equalTo(streamArn))
|
||||
.extract().path("StreamDescription.Shards[0].ShardId");
|
||||
String iterator = streams(A_WEST, "GetShardIterator", "{\"StreamArn\": \"" + streamArn
|
||||
+ "\", \"ShardId\": \"" + shardId + "\", \"ShardIteratorType\": \"TRIM_HORIZON\"}")
|
||||
.statusCode(200)
|
||||
.extract().path("ShardIterator");
|
||||
|
||||
streams(A_WEST, "GetRecords", "{\"ShardIterator\": \"" + iterator + "\"}")
|
||||
.statusCode(200)
|
||||
.body("Records", hasSize(1))
|
||||
.body("Records[0].eventName", equalTo("INSERT"))
|
||||
.body("Records[0].awsRegion", equalTo("eu-west-1"))
|
||||
.body("Records[0].dynamodb.Keys.pk.S", equalTo("streamed"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStreamOfAnotherAccountIsNotFound() {
|
||||
String table = tableName("foreign-stream");
|
||||
String streamArn = streamedTableWithOneItem(A_EAST, table);
|
||||
|
||||
streams(B_EAST, "DescribeStream", "{\"StreamArn\": \"" + streamArn + "\"}")
|
||||
.statusCode(400)
|
||||
.body("__type", endsWith("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theStreamReaderReadsTheSameRecordsWithStreamCheckpoints() {
|
||||
String table = tableName("reader");
|
||||
String streamArn = streamedTableWithOneItem(A_WEST, table);
|
||||
|
||||
Stream stream = Stream.of(streamArn);
|
||||
List<Shard> shards = streamReader.shards(stream);
|
||||
Cursor cursor = streamReader.getShardIterator(stream, shards.get(0).shardId(), Position.TRIM_HORIZON, null);
|
||||
RecordsPage page = streamReader.getRecords(cursor, 10);
|
||||
|
||||
assertEquals(1, page.records().size());
|
||||
JsonNode record = page.records().get(0).awsRecord();
|
||||
assertEquals("INSERT", record.path("eventName").asText());
|
||||
assertEquals("eu-west-1", record.path("awsRegion").asText());
|
||||
assertEquals("streamed", record.path("dynamodb").path("Keys").path("pk").path("S").asText());
|
||||
assertEquals(CheckpointLifetime.STREAM, streamReader.checkpointLifetime());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theDirectDeleteRemovesAProtectedTable() {
|
||||
String table = tableName("protected");
|
||||
createTable(A_WEST, table, ", \"DeletionProtectionEnabled\": true").statusCode(200);
|
||||
dynamoDb(A_WEST, "DeleteTable", "{\"TableName\": \"" + table + "\"}").statusCode(400);
|
||||
|
||||
dynamoDbFacade.tables().deleteTable(new Scope(A_WEST.account(), A_WEST.region()), table);
|
||||
created.clear();
|
||||
|
||||
dynamoDb(A_WEST, "DescribeTable", "{\"TableName\": \"" + table + "\"}")
|
||||
.statusCode(400)
|
||||
.body("__type", endsWith("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetIsRefused() {
|
||||
given().when().post("/_floci/state/reset").then().statusCode(409);
|
||||
}
|
||||
|
||||
@Test
|
||||
void infoReportsTheLocalBackend() {
|
||||
given()
|
||||
.when().get("/_floci/info")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("dynamodb_backend", equalTo("local"));
|
||||
}
|
||||
|
||||
private String streamedTableWithOneItem(Caller caller, String table) {
|
||||
String streamArn = createTable(caller, table, STREAMED)
|
||||
.statusCode(200)
|
||||
.extract().path("TableDescription.LatestStreamArn");
|
||||
putItem(caller, table, "streamed");
|
||||
return streamArn;
|
||||
}
|
||||
|
||||
private ValidatableResponse createTable(Caller caller, String table, String extraFields) {
|
||||
ValidatableResponse response = dynamoDb(caller, "CreateTable", """
|
||||
{
|
||||
"TableName": "%s",
|
||||
"KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
|
||||
"AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}],
|
||||
"BillingMode": "PAY_PER_REQUEST"%s
|
||||
}
|
||||
""".formatted(table, extraFields));
|
||||
created.add(new CreatedTable(caller, table));
|
||||
return response;
|
||||
}
|
||||
|
||||
private static void putItem(Caller caller, String table, String pk) {
|
||||
dynamoDb(caller, "PutItem", "{\"TableName\": \"" + table + "\", \"Item\": {\"pk\": {\"S\": \"" + pk + "\"}}}")
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
private static ValidatableResponse scanCount(Caller caller, String table) {
|
||||
return dynamoDb(caller, "Scan", "{\"TableName\": \"" + table + "\"}").statusCode(200);
|
||||
}
|
||||
|
||||
private static ValidatableResponse dynamoDb(Caller caller, String action, String body) {
|
||||
return send(caller, "DynamoDB_20120810." + action, body);
|
||||
}
|
||||
|
||||
private static ValidatableResponse streams(Caller caller, String action, String body) {
|
||||
return send(caller, "DynamoDBStreams_20120810." + action, body);
|
||||
}
|
||||
|
||||
private static ValidatableResponse send(Caller caller, String target, String body) {
|
||||
return given()
|
||||
.header("X-Amz-Target", target)
|
||||
.header("Authorization", caller.authorization())
|
||||
.contentType(CONTENT_TYPE)
|
||||
.body(body)
|
||||
.when()
|
||||
.post("/")
|
||||
.then();
|
||||
}
|
||||
|
||||
private static String tableArn(Caller caller, String table) {
|
||||
return "arn:aws:dynamodb:" + caller.region() + ":" + caller.account() + ":table/" + table;
|
||||
}
|
||||
|
||||
private static String tableName(String purpose) {
|
||||
return "local-it-" + purpose + "-" + UUID.randomUUID();
|
||||
}
|
||||
|
||||
private static String randomAccount() {
|
||||
return Long.toString(ThreadLocalRandom.current().nextLong(100_000_000_000L, 1_000_000_000_000L));
|
||||
}
|
||||
|
||||
private static String otherAccountThan(String account) {
|
||||
String other = randomAccount();
|
||||
while (other.equals(account)) {
|
||||
other = randomAccount();
|
||||
}
|
||||
return other;
|
||||
}
|
||||
}
|
||||
+783
@@ -0,0 +1,783 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb.backend;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.resource.ExplorerResource;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbItemAccess.ScanPage;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Api;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Call;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Reply;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Scope;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.GlobalSecondaryIndex;
|
||||
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 org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InOrder;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ConnectException;
|
||||
import java.net.URI;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
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;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.atLeastOnce;
|
||||
import static org.mockito.Mockito.inOrder;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** The DynamoDB Local engine: identity translation, Floci-held tags, typed operations and lifecycle. */
|
||||
class DynamoDbLocalBackendTest {
|
||||
|
||||
private static final String ACCOUNT = "123456789012";
|
||||
private static final String REGION = "eu-west-1";
|
||||
private static final Scope SCOPE = new Scope(ACCOUNT, REGION);
|
||||
private static final String LOCAL = "arn:aws:dynamodb:ddblocal:000000000000:";
|
||||
private static final String PUBLIC = "arn:aws:dynamodb:eu-west-1:123456789012:";
|
||||
private static final String ORDERS_ARN = PUBLIC + "table/orders";
|
||||
private static final String STREAM_RESOURCE = "table/orders/stream/2026-09-27T00:03:07.048";
|
||||
private static final String REPLICAS_UNSUPPORTED = "Replicas are not supported by the DynamoDB Local backend";
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper().findAndRegisterModules();
|
||||
private final DynamoDbLocalClient client = mock(DynamoDbLocalClient.class);
|
||||
private final AccountAwareStorageBackend<Map<String, String>> tags =
|
||||
AccountAwareStorageBackend.inMemory("000000000000");
|
||||
private DynamoDbLocalBackend backend;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
when(client.endpoint()).thenReturn(URI.create("http://local:8000"));
|
||||
backend = new DynamoDbLocalBackend(client, tags, mapper, Duration.ofSeconds(5));
|
||||
}
|
||||
|
||||
private JsonNode json(String text) throws IOException {
|
||||
return mapper.readTree(text);
|
||||
}
|
||||
|
||||
private JsonNode normalized(JsonNode node) throws IOException {
|
||||
return mapper.readTree(mapper.writeValueAsBytes(node));
|
||||
}
|
||||
|
||||
private void answer(Api api, String action, int status, String body) throws Exception {
|
||||
when(client.send(any(), eq(api), eq(action), any()))
|
||||
.thenAnswer(invocation -> new Reply(status, json(body), Map.of()));
|
||||
}
|
||||
|
||||
private void answer(String action, int status, String body) throws Exception {
|
||||
answer(Api.DYNAMODB, action, status, body);
|
||||
}
|
||||
|
||||
private List<JsonNode> sentBodies(Api api, String action) throws Exception {
|
||||
ArgumentCaptor<JsonNode> body = ArgumentCaptor.forClass(JsonNode.class);
|
||||
verify(client, atLeastOnce()).send(any(), eq(api), eq(action), body.capture());
|
||||
List<JsonNode> bodies = new ArrayList<>();
|
||||
for (JsonNode value : body.getAllValues()) {
|
||||
bodies.add(normalized(value));
|
||||
}
|
||||
return bodies;
|
||||
}
|
||||
|
||||
private JsonNode sent(Api api, String action) throws Exception {
|
||||
List<JsonNode> bodies = sentBodies(api, action);
|
||||
return bodies.get(bodies.size() - 1);
|
||||
}
|
||||
|
||||
private JsonNode sent(String action) throws Exception {
|
||||
return sent(Api.DYNAMODB, action);
|
||||
}
|
||||
|
||||
private void neverSent(String action) throws Exception {
|
||||
verify(client, never()).send(any(), any(), eq(action), any());
|
||||
}
|
||||
|
||||
private Reply execute(Api api, String action, String body) throws Exception {
|
||||
return backend.execute(new Call(SCOPE, api, action, json(body)));
|
||||
}
|
||||
|
||||
private Reply execute(String action, String body) throws Exception {
|
||||
return execute(Api.DYNAMODB, action, body);
|
||||
}
|
||||
|
||||
private void answerOrdersTable() throws Exception {
|
||||
answer("DescribeTable", 200, "{\"Table\":{\"TableName\":\"orders\",\"TableArn\":\"" + LOCAL
|
||||
+ "table/orders\",\"TableStatus\":\"ACTIVE\"}}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void tableArnTableNameBecomesShortName() throws Exception {
|
||||
answer("GetItem", 200, "{}");
|
||||
|
||||
execute("GetItem", "{\"TableName\":\"" + ORDERS_ARN + "\",\"Key\":{\"pk\":{\"S\":\"a\"}}}");
|
||||
|
||||
assertEquals(json("{\"TableName\":\"orders\",\"Key\":{\"pk\":{\"S\":\"a\"}}}"), sent("GetItem"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void requestItemsArnKeysBecomeShortNames() throws Exception {
|
||||
answer("BatchWriteItem", 200, "{\"UnprocessedItems\":{}}");
|
||||
|
||||
execute("BatchWriteItem", "{\"RequestItems\":{\"" + ORDERS_ARN + "\":[{\"PutRequest\":{\"Item\":"
|
||||
+ "{\"pk\":{\"S\":\"a\"}}}}],\"users\":[{\"DeleteRequest\":{\"Key\":{\"pk\":{\"S\":\"b\"}}}}]}}");
|
||||
|
||||
JsonNode requestItems = sent("BatchWriteItem").path("RequestItems");
|
||||
List<String> names = new ArrayList<>();
|
||||
requestItems.fieldNames().forEachRemaining(names::add);
|
||||
assertEquals(List.of("orders", "users"), names);
|
||||
assertEquals(json("[{\"PutRequest\":{\"Item\":{\"pk\":{\"S\":\"a\"}}}}]"), requestItems.path("orders"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void transactItemsNestedTableNamesTranslated() throws Exception {
|
||||
answer("TransactWriteItems", 200, "{}");
|
||||
|
||||
execute("TransactWriteItems", "{\"TransactItems\":["
|
||||
+ "{\"Put\":{\"TableName\":\"" + ORDERS_ARN + "\",\"Item\":{\"pk\":{\"S\":\"a\"}}}},"
|
||||
+ "{\"ConditionCheck\":{\"TableName\":\"" + PUBLIC + "table/users\",\"Key\":{\"pk\":{\"S\":\"b\"}},"
|
||||
+ "\"ConditionExpression\":\"attribute_exists(pk)\"}},"
|
||||
+ "{\"Delete\":{\"TableName\":\"audit\",\"Key\":{\"pk\":{\"S\":\"c\"}}}}]}");
|
||||
|
||||
JsonNode items = sent("TransactWriteItems").path("TransactItems");
|
||||
assertEquals("orders", items.path(0).path("Put").path("TableName").asText());
|
||||
assertEquals("users", items.path(1).path("ConditionCheck").path("TableName").asText());
|
||||
assertEquals("audit", items.path(2).path("Delete").path("TableName").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void foreignAccountOrPartitionArnNotFound() throws Exception {
|
||||
for (String foreign : List.of("arn:aws:dynamodb:eu-west-1:999999999999:table/orders",
|
||||
"arn:aws-cn:dynamodb:eu-west-1:123456789012:table/orders")) {
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> execute("GetItem", "{\"TableName\":\"" + foreign + "\",\"Key\":{}}"));
|
||||
|
||||
assertEquals("ResourceNotFoundException", error.getErrorCode());
|
||||
assertEquals("Requested resource not found: Table: " + foreign + " not found", error.getMessage());
|
||||
}
|
||||
neverSent("GetItem");
|
||||
}
|
||||
|
||||
@Test
|
||||
void requestItemsNamingOneTableTwiceRejected() throws Exception {
|
||||
AwsException error = assertThrows(AwsException.class, () -> execute("BatchWriteItem",
|
||||
"{\"RequestItems\":{\"" + ORDERS_ARN + "\":[],\"orders\":[]}}"));
|
||||
|
||||
assertEquals("ValidationException", error.getErrorCode());
|
||||
neverSent("BatchWriteItem");
|
||||
}
|
||||
|
||||
@Test
|
||||
void foreignRegionArnRejected() throws Exception {
|
||||
AwsException error = assertThrows(AwsException.class, () -> execute("GetItem",
|
||||
"{\"TableName\":\"arn:aws:dynamodb:us-east-1:123456789012:table/orders\",\"Key\":{}}"));
|
||||
|
||||
assertEquals("ValidationException", error.getErrorCode());
|
||||
assertEquals("Region 'us-east-1' in ARN does not match request region 'eu-west-1'", error.getMessage());
|
||||
neverSent("GetItem");
|
||||
}
|
||||
|
||||
@Test
|
||||
void createTableArnNameLeftForLocal() throws Exception {
|
||||
answer("CreateTable", 400, "{\"__type\":\"com.amazonaws.dynamodb.v20120810#ValidationException\","
|
||||
+ "\"message\":\"Invalid table name\"}");
|
||||
|
||||
Reply reply = execute("CreateTable", "{\"TableName\":\"" + ORDERS_ARN + "\"}");
|
||||
|
||||
assertEquals(ORDERS_ARN, sent("CreateTable").path("TableName").asText());
|
||||
assertEquals(400, reply.status());
|
||||
}
|
||||
|
||||
@Test
|
||||
void streamArnTranslatedToLocalPrefix() throws Exception {
|
||||
answer(Api.DYNAMODB_STREAMS, "DescribeStream", 200, "{\"StreamDescription\":{}}");
|
||||
|
||||
execute(Api.DYNAMODB_STREAMS, "DescribeStream", "{\"StreamArn\":\"" + PUBLIC + STREAM_RESOURCE + "\"}");
|
||||
|
||||
assertEquals(LOCAL + STREAM_RESOURCE, sent(Api.DYNAMODB_STREAMS, "DescribeStream").path("StreamArn").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listStreamsPagesWithPublicStreamArns() throws Exception {
|
||||
answer(Api.DYNAMODB_STREAMS, "ListStreams", 200,
|
||||
"{\"LastEvaluatedStreamArn\":\"" + LOCAL + STREAM_RESOURCE + "\"}");
|
||||
|
||||
Reply reply = execute(Api.DYNAMODB_STREAMS, "ListStreams",
|
||||
"{\"ExclusiveStartStreamArn\":\"" + PUBLIC + STREAM_RESOURCE + "\"}");
|
||||
|
||||
assertEquals(LOCAL + STREAM_RESOURCE,
|
||||
sent(Api.DYNAMODB_STREAMS, "ListStreams").path("ExclusiveStartStreamArn").asText());
|
||||
assertEquals(PUBLIC + STREAM_RESOURCE, reply.body().path("LastEvaluatedStreamArn").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void foreignStreamArnNotFound() throws Exception {
|
||||
for (String foreign : List.of("arn:aws:dynamodb:eu-west-1:999999999999:" + STREAM_RESOURCE,
|
||||
"arn:aws:dynamodb:us-east-1:123456789012:" + STREAM_RESOURCE,
|
||||
"arn:aws-cn:dynamodb:eu-west-1:123456789012:" + STREAM_RESOURCE)) {
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> execute(Api.DYNAMODB_STREAMS, "DescribeStream", "{\"StreamArn\":\"" + foreign + "\"}"));
|
||||
|
||||
assertEquals("ResourceNotFoundException", error.getErrorCode());
|
||||
assertEquals("Requested resource not found: Stream: " + foreign + " not found", error.getMessage());
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
}
|
||||
neverSent("DescribeStream");
|
||||
}
|
||||
|
||||
@Test
|
||||
void publicArnsInReply() throws Exception {
|
||||
answer("DescribeTable", 200, "{\"Table\":{\"TableName\":\"orders\",\"TableArn\":\"" + LOCAL + "table/orders\","
|
||||
+ "\"GlobalSecondaryIndexes\":[{\"IndexName\":\"g\","
|
||||
+ "\"IndexArn\":\"" + LOCAL + "table/orders/index/g\"}],"
|
||||
+ "\"LatestStreamArn\":\"" + LOCAL + STREAM_RESOURCE + "\"}}");
|
||||
|
||||
JsonNode table = execute("DescribeTable", "{\"TableName\":\"orders\"}").body().path("Table");
|
||||
|
||||
assertEquals(ORDERS_ARN, table.path("TableArn").asText());
|
||||
assertEquals(ORDERS_ARN + "/index/g", table.path("GlobalSecondaryIndexes").path(0).path("IndexArn").asText());
|
||||
assertEquals(PUBLIC + STREAM_RESOURCE, table.path("LatestStreamArn").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void errorMessageArnRewritten() throws Exception {
|
||||
answer("DescribeTable", 400, "{\"__type\":\"com.amazonaws.dynamodb.v20120810#ResourceNotFoundException\","
|
||||
+ "\"message\":\"Requested resource not found: Table: " + LOCAL + "table/orders not found\"}");
|
||||
|
||||
Reply reply = execute("DescribeTable", "{\"TableName\":\"orders\"}");
|
||||
|
||||
assertEquals("Requested resource not found: Table: " + ORDERS_ARN + " not found",
|
||||
reply.body().path("message").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void recordAwsRegionRewritten() throws Exception {
|
||||
answer(Api.DYNAMODB_STREAMS, "GetRecords", 200,
|
||||
"{\"Records\":[{\"eventName\":\"INSERT\",\"awsRegion\":\"ddblocal\",\"dynamodb\":{}}]}");
|
||||
|
||||
Reply reply = execute(Api.DYNAMODB_STREAMS, "GetRecords", "{\"ShardIterator\":\"it\"}");
|
||||
|
||||
assertEquals(REGION, reply.body().path("Records").path(0).path("awsRegion").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void arnLookingItemAttributeUntouched() throws Exception {
|
||||
String item = "{\"TableArn\":{\"S\":\"" + LOCAL + "table/x\"},"
|
||||
+ "\"StreamArn\":{\"S\":\"arn:aws:dynamodb:us-east-1:999999999999:" + STREAM_RESOURCE + "\"},"
|
||||
+ "\"TableName\":{\"S\":\"" + PUBLIC + "table/other\"},"
|
||||
+ "\"awsRegion\":{\"S\":\"ddblocal\"}}";
|
||||
answer("PutItem", 200, "{}");
|
||||
answer("GetItem", 200, "{\"Item\":" + item + "}");
|
||||
|
||||
execute("PutItem", "{\"TableName\":\"orders\",\"Item\":" + item + "}");
|
||||
Reply reply = execute("GetItem", "{\"TableName\":\"orders\",\"Key\":{\"pk\":{\"S\":\"a\"}}}");
|
||||
|
||||
assertEquals(json(item), sent("PutItem").path("Item"));
|
||||
assertEquals(json(item), reply.body().path("Item"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void callerBodyNotMutated() throws Exception {
|
||||
answer("GetItem", 200, "{}");
|
||||
JsonNode body = json("{\"TableName\":\"" + ORDERS_ARN + "\",\"Key\":{\"pk\":{\"S\":\"a\"}}}");
|
||||
JsonNode original = body.deepCopy();
|
||||
|
||||
backend.execute(new Call(SCOPE, Api.DYNAMODB, "GetItem", body));
|
||||
|
||||
assertEquals(original, body);
|
||||
}
|
||||
|
||||
@Test
|
||||
void sendsUnderCallerScope() throws Exception {
|
||||
answer("DescribeTable", 200, "{\"Table\":{}}");
|
||||
Scope caller = new Scope("210987654321", "ap-south-1");
|
||||
|
||||
backend.execute(new Call(caller, Api.DYNAMODB, "DescribeTable", json("{\"TableName\":\"orders\"}")));
|
||||
|
||||
ArgumentCaptor<Scope> scope = ArgumentCaptor.forClass(Scope.class);
|
||||
verify(client).send(scope.capture(), eq(Api.DYNAMODB), eq("DescribeTable"), any());
|
||||
assertEquals(caller, scope.getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void ioFailureIsInternalServerError() throws Exception {
|
||||
when(client.send(any(), any(), any(), any())).thenThrow(new IOException("boom"));
|
||||
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> execute("DescribeTable", "{\"TableName\":\"orders\"}"));
|
||||
|
||||
assertEquals("InternalServerError", error.getErrorCode());
|
||||
assertEquals(500, error.getHttpStatus());
|
||||
assertEquals("DynamoDB Local at http://local:8000 did not answer: java.io.IOException: boom",
|
||||
error.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void untaggedTableListsNoTags() throws Exception {
|
||||
answerOrdersTable();
|
||||
|
||||
assertEquals(Map.of(), backend.listTagsOfResource(SCOPE, ORDERS_ARN));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagAbsentTableFails() throws Exception {
|
||||
answer("DescribeTable", 400, "{\"__type\":\"com.amazonaws.dynamodb.v20120810#ResourceNotFoundException\","
|
||||
+ "\"message\":\"Requested resource not found\"}");
|
||||
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> backend.tagResource(SCOPE, ORDERS_ARN, Map.of("env", "dev")));
|
||||
|
||||
assertEquals("ResourceNotFoundException", error.getErrorCode());
|
||||
assertTrue(tags.keysForAccount(ACCOUNT).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void wireListTagsOfAMissingTableIsAccessDenied() throws Exception {
|
||||
answer("DescribeTable", 400, "{\"__type\":\"com.amazonaws.dynamodb.v20120810#ResourceNotFoundException\","
|
||||
+ "\"message\":\"Requested resource not found\"}");
|
||||
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> execute("ListTagsOfResource", "{\"ResourceArn\":\"" + ORDERS_ARN + "\"}"));
|
||||
|
||||
assertEquals("AccessDeniedException", error.getErrorCode());
|
||||
assertEquals("User is not authorized to perform: dynamodb:ListTagsOfResource on resource: " + ORDERS_ARN,
|
||||
error.getMessage());
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagArnOfAnUnknownPartitionIsValidation() throws Exception {
|
||||
String arn = "arn:notaws:dynamodb:eu-west-1:123456789012:table/orders";
|
||||
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> execute("TagResource", "{\"ResourceArn\":\"" + arn + "\",\"Tags\":[]}"));
|
||||
|
||||
assertEquals("ValidationException", error.getErrorCode());
|
||||
neverSent("DescribeTable");
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagArnOfAnotherRegionOrPartitionIsNotFound() throws Exception {
|
||||
for (String foreign : List.of("arn:aws:dynamodb:us-east-1:123456789012:table/orders",
|
||||
"arn:aws-cn:dynamodb:cn-north-1:123456789012:table/orders")) {
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> execute("UntagResource", "{\"ResourceArn\":\"" + foreign + "\",\"TagKeys\":[]}"));
|
||||
|
||||
assertEquals("ResourceNotFoundException", error.getErrorCode());
|
||||
}
|
||||
neverSent("DescribeTable");
|
||||
}
|
||||
|
||||
@Test
|
||||
void createTableRecordsRequestTags() throws Exception {
|
||||
answer("CreateTable", 200, "{\"TableDescription\":{\"TableName\":\"orders\",\"TableArn\":\"" + LOCAL
|
||||
+ "table/orders\"}}");
|
||||
answerOrdersTable();
|
||||
|
||||
execute("CreateTable", "{\"TableName\":\"orders\",\"Tags\":[{\"Key\":\"env\",\"Value\":\"dev\"}]}");
|
||||
|
||||
assertEquals(Map.of("env", "dev"), backend.listTagsOfResource(SCOPE, ORDERS_ARN));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteTableDropsTags() throws Exception {
|
||||
tags.putForAccount(ACCOUNT, REGION + "/orders", Map.of("env", "dev"));
|
||||
answer("DeleteTable", 200, "{\"TableDescription\":{\"TableName\":\"orders\",\"TableStatus\":\"DELETING\"}}");
|
||||
|
||||
execute("DeleteTable", "{\"TableName\":\"" + ORDERS_ARN + "\"}");
|
||||
|
||||
assertTrue(tags.getForAccount(ACCOUNT, REGION + "/orders").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void directDeleteLiftsDeletionProtectionFirst() throws Exception {
|
||||
answer("DescribeTable", 200, "{\"Table\":{\"TableName\":\"orders\",\"DeletionProtectionEnabled\":true}}");
|
||||
answer("UpdateTable", 200, "{\"TableDescription\":{\"TableName\":\"orders\"}}");
|
||||
answer("DeleteTable", 200, "{\"TableDescription\":{\"TableName\":\"orders\"}}");
|
||||
|
||||
backend.deleteTable(SCOPE, "orders");
|
||||
|
||||
InOrder order = inOrder(client);
|
||||
order.verify(client).send(any(), eq(Api.DYNAMODB), eq("UpdateTable"),
|
||||
eq(json("{\"TableName\":\"orders\",\"DeletionProtectionEnabled\":false}")));
|
||||
order.verify(client).send(any(), eq(Api.DYNAMODB), eq("DeleteTable"), eq(json("{\"TableName\":\"orders\"}")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void directDeleteOfAnUnprotectedTableSendsOnlyDeleteTable() throws Exception {
|
||||
answer("DescribeTable", 200, "{\"Table\":{\"TableName\":\"orders\",\"DeletionProtectionEnabled\":false}}");
|
||||
answer("DeleteTable", 200, "{\"TableDescription\":{\"TableName\":\"orders\"}}");
|
||||
|
||||
backend.deleteTable(SCOPE, "orders");
|
||||
|
||||
neverSent("UpdateTable");
|
||||
assertEquals(json("{\"TableName\":\"orders\"}"), sent("DeleteTable"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void wireTagRoundTrip() throws Exception {
|
||||
answerOrdersTable();
|
||||
|
||||
Reply tagged = execute("TagResource", "{\"ResourceArn\":\"" + ORDERS_ARN + "\",\"Tags\":["
|
||||
+ "{\"Key\":\"env\",\"Value\":\"dev\"},{\"Key\":\"team\",\"Value\":\"a\"}]}");
|
||||
JsonNode listed = execute("ListTagsOfResource", "{\"ResourceArn\":\"" + ORDERS_ARN + "\"}").body();
|
||||
Reply untagged = execute("UntagResource", "{\"ResourceArn\":\"" + ORDERS_ARN + "\",\"TagKeys\":[\"env\"]}");
|
||||
JsonNode remaining = execute("ListTagsOfResource", "{\"ResourceArn\":\"" + ORDERS_ARN + "\"}").body();
|
||||
|
||||
assertEquals(200, tagged.status());
|
||||
assertEquals(json("{}"), tagged.body());
|
||||
assertEquals(json("{\"Tags\":[{\"Key\":\"env\",\"Value\":\"dev\"},"
|
||||
+ "{\"Key\":\"team\",\"Value\":\"a\"}]}"), listed);
|
||||
assertEquals(200, untagged.status());
|
||||
assertEquals(json("{\"Tags\":[{\"Key\":\"team\",\"Value\":\"a\"}]}"), remaining);
|
||||
neverSent("TagResource");
|
||||
neverSent("UntagResource");
|
||||
neverSent("ListTagsOfResource");
|
||||
}
|
||||
|
||||
@Test
|
||||
void replicaUpdatesRejected() throws Exception {
|
||||
AwsException wire = assertThrows(AwsException.class, () -> execute("UpdateTable",
|
||||
"{\"TableName\":\"orders\",\"ReplicaUpdates\":[{\"Create\":{\"RegionName\":\"us-east-1\"}}]}"));
|
||||
AwsException typed = assertThrows(AwsException.class,
|
||||
() -> backend.applyReplicaUpdates(SCOPE, "orders", List.of("us-east-1"), List.of()));
|
||||
|
||||
for (AwsException error : List.of(wire, typed)) {
|
||||
assertEquals("ValidationException", error.getErrorCode());
|
||||
assertEquals(REPLICAS_UNSUPPORTED, error.getMessage());
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
}
|
||||
neverSent("UpdateTable");
|
||||
}
|
||||
|
||||
@Test
|
||||
void ensureGlobalTableDescribes() throws Exception {
|
||||
answerOrdersTable();
|
||||
|
||||
TableDefinition table = backend.ensureGlobalTable(SCOPE, "orders");
|
||||
|
||||
assertEquals("orders", table.getTableName());
|
||||
assertEquals(ORDERS_ARN, table.getTableArn());
|
||||
assertEquals("", table.getTableId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createTableTypedProvisionedJson() throws Exception {
|
||||
answer("CreateTable", 200, "{\"TableDescription\":{\"TableName\":\"orders\",\"TableArn\":\"" + LOCAL
|
||||
+ "table/orders\"}}");
|
||||
|
||||
TableDefinition table = backend.createTable(SCOPE, "orders",
|
||||
List.of(new KeySchemaElement("pk", "HASH"), new KeySchemaElement("sk", "RANGE")),
|
||||
List.of(new AttributeDefinition("pk", "S"), new AttributeDefinition("sk", "S"),
|
||||
new AttributeDefinition("g", "S"), new AttributeDefinition("l", "N")),
|
||||
3L, 4L,
|
||||
List.of(new GlobalSecondaryIndex("gsi1", List.of(new KeySchemaElement("g", "HASH")), null,
|
||||
"INCLUDE", List.of("a"))),
|
||||
List.of(new LocalSecondaryIndex("lsi1", List.of(new KeySchemaElement("pk", "HASH"),
|
||||
new KeySchemaElement("l", "RANGE")), null, "KEYS_ONLY")));
|
||||
|
||||
assertEquals(json("""
|
||||
{"TableName":"orders",
|
||||
"KeySchema":[{"AttributeName":"pk","KeyType":"HASH"},{"AttributeName":"sk","KeyType":"RANGE"}],
|
||||
"AttributeDefinitions":[{"AttributeName":"pk","AttributeType":"S"},
|
||||
{"AttributeName":"sk","AttributeType":"S"},{"AttributeName":"g","AttributeType":"S"},
|
||||
{"AttributeName":"l","AttributeType":"N"}],
|
||||
"BillingMode":"PROVISIONED",
|
||||
"ProvisionedThroughput":{"ReadCapacityUnits":3,"WriteCapacityUnits":4},
|
||||
"GlobalSecondaryIndexes":[{"IndexName":"gsi1","KeySchema":[{"AttributeName":"g","KeyType":"HASH"}],
|
||||
"Projection":{"ProjectionType":"INCLUDE","NonKeyAttributes":["a"]},
|
||||
"ProvisionedThroughput":{"ReadCapacityUnits":3,"WriteCapacityUnits":4}}],
|
||||
"LocalSecondaryIndexes":[{"IndexName":"lsi1","KeySchema":[{"AttributeName":"pk","KeyType":"HASH"},
|
||||
{"AttributeName":"l","KeyType":"RANGE"}],"Projection":{"ProjectionType":"KEYS_ONLY"}}]}
|
||||
"""), sent("CreateTable"));
|
||||
assertEquals(ORDERS_ARN, table.getTableArn());
|
||||
assertEquals(List.of(REGION + "/orders"), List.copyOf(tags.keysForAccount(ACCOUNT)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createTableTypedOnDemandJson() throws Exception {
|
||||
answer("CreateTable", 200, "{\"TableDescription\":{\"TableName\":\"orders\"}}");
|
||||
GlobalSecondaryIndex gsi = new GlobalSecondaryIndex();
|
||||
gsi.setIndexName("gsi1");
|
||||
gsi.setKeySchema(List.of(new KeySchemaElement("g", "HASH")));
|
||||
|
||||
backend.createTable(SCOPE, "orders", List.of(new KeySchemaElement("pk", "HASH")),
|
||||
List.of(new AttributeDefinition("pk", "S"), new AttributeDefinition("g", "S")),
|
||||
null, null, List.of(gsi), List.of());
|
||||
|
||||
assertEquals(json("""
|
||||
{"TableName":"orders",
|
||||
"KeySchema":[{"AttributeName":"pk","KeyType":"HASH"}],
|
||||
"AttributeDefinitions":[{"AttributeName":"pk","AttributeType":"S"},
|
||||
{"AttributeName":"g","AttributeType":"S"}],
|
||||
"BillingMode":"PAY_PER_REQUEST",
|
||||
"GlobalSecondaryIndexes":[{"IndexName":"gsi1","KeySchema":[{"AttributeName":"g","KeyType":"HASH"}],
|
||||
"Projection":{"ProjectionType":"ALL"}}]}
|
||||
"""), sent("CreateTable"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeTableMapsStreamFields() throws Exception {
|
||||
answer("DescribeTable", 200, "{\"Table\":{\"TableName\":\"orders\",\"TableArn\":\"" + LOCAL + "table/orders\","
|
||||
+ "\"CreationDateTime\":1.790463342979E9,"
|
||||
+ "\"StreamSpecification\":{\"StreamEnabled\":true,\"StreamViewType\":\"KEYS_ONLY\"},"
|
||||
+ "\"LatestStreamArn\":\"" + LOCAL + STREAM_RESOURCE + "\"}}");
|
||||
|
||||
TableDefinition table = backend.describeTable(SCOPE, "orders");
|
||||
|
||||
assertTrue(table.isStreamEnabled());
|
||||
assertEquals("KEYS_ONLY", table.getStreamViewType());
|
||||
assertEquals(PUBLIC + STREAM_RESOURCE, table.getStreamArn());
|
||||
assertEquals(Instant.ofEpochMilli(1790463342979L), table.getCreationDateTime());
|
||||
}
|
||||
|
||||
@Test
|
||||
void findTableAbsentIsEmpty() throws Exception {
|
||||
answer("DescribeTable", 400, "{\"__type\":\"com.amazonaws.dynamodb.v20120810#ResourceNotFoundException\","
|
||||
+ "\"message\":\"Requested resource not found\"}");
|
||||
|
||||
assertEquals(Optional.empty(), backend.findTable(SCOPE, "orders"));
|
||||
}
|
||||
|
||||
private void answerStreamingOrdersTable(String viewType) throws Exception {
|
||||
answer("DescribeTable", 200, "{\"Table\":{\"TableName\":\"orders\","
|
||||
+ "\"StreamSpecification\":{\"StreamEnabled\":true,\"StreamViewType\":\"" + viewType + "\"},"
|
||||
+ "\"LatestStreamArn\":\"" + LOCAL + STREAM_RESOURCE + "\"}}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void enableStreamIdempotent() throws Exception {
|
||||
answerStreamingOrdersTable("NEW_AND_OLD_IMAGES");
|
||||
|
||||
TableDefinition unspecified = backend.enableStream(SCOPE, "orders", null);
|
||||
TableDefinition same = backend.enableStream(SCOPE, "orders", "NEW_AND_OLD_IMAGES");
|
||||
|
||||
assertEquals(PUBLIC + STREAM_RESOURCE, unspecified.getStreamArn());
|
||||
assertEquals("NEW_AND_OLD_IMAGES", same.getStreamViewType());
|
||||
neverSent("UpdateTable");
|
||||
}
|
||||
|
||||
@Test
|
||||
void enableStreamWithNewViewTypeRestartsStream() throws Exception {
|
||||
answerStreamingOrdersTable("NEW_AND_OLD_IMAGES");
|
||||
answer("UpdateTable", 200, "{\"TableDescription\":{\"TableName\":\"orders\","
|
||||
+ "\"StreamSpecification\":{\"StreamEnabled\":true,\"StreamViewType\":\"KEYS_ONLY\"},"
|
||||
+ "\"LatestStreamArn\":\"" + LOCAL + STREAM_RESOURCE + "\"}}");
|
||||
|
||||
TableDefinition table = backend.enableStream(SCOPE, "orders", "KEYS_ONLY");
|
||||
|
||||
assertEquals(List.of(
|
||||
json("{\"TableName\":\"orders\",\"StreamSpecification\":{\"StreamEnabled\":false}}"),
|
||||
json("{\"TableName\":\"orders\",\"StreamSpecification\":{\"StreamEnabled\":true,"
|
||||
+ "\"StreamViewType\":\"KEYS_ONLY\"}}")),
|
||||
sentBodies(Api.DYNAMODB, "UpdateTable"));
|
||||
assertEquals("KEYS_ONLY", table.getStreamViewType());
|
||||
}
|
||||
|
||||
@Test
|
||||
void disableStreamIdempotent() throws Exception {
|
||||
answerOrdersTable();
|
||||
|
||||
TableDefinition table = backend.disableStream(SCOPE, "orders");
|
||||
|
||||
assertFalse(table.isStreamEnabled());
|
||||
assertNull(table.getStreamArn());
|
||||
neverSent("UpdateTable");
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateItemReturnsOnlyImages() throws Exception {
|
||||
answer("UpdateItem", 200, "{\"Attributes\":{\"pk\":{\"S\":\"a\"},\"n\":{\"N\":\"2\"}}}");
|
||||
JsonNode key = json("{\"pk\":{\"S\":\"a\"}}");
|
||||
|
||||
JsonNode updatedOnly = backend.updateItem(SCOPE, "orders", key, null, "SET n = :n", null,
|
||||
json("{\":n\":{\"N\":\"2\"}}"), "UPDATED_NEW", null);
|
||||
JsonNode allNew = backend.updateItem(SCOPE, "orders", key, null, "SET n = :n", null,
|
||||
json("{\":n\":{\"N\":\"2\"}}"), "ALL_NEW", null);
|
||||
|
||||
assertNull(updatedOnly);
|
||||
assertEquals(json("{\"pk\":{\"S\":\"a\"},\"n\":{\"N\":\"2\"}}"), allNew);
|
||||
assertEquals(json("{\"TableName\":\"orders\",\"Key\":{\"pk\":{\"S\":\"a\"}},"
|
||||
+ "\"UpdateExpression\":\"SET n = :n\","
|
||||
+ "\"ExpressionAttributeValues\":{\":n\":{\"N\":\"2\"}},\"ReturnValues\":\"ALL_NEW\"}"),
|
||||
sent("UpdateItem"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void scanPage() throws Exception {
|
||||
answer("Scan", 200, "{\"Items\":[{\"pk\":{\"S\":\"a\"}},{\"pk\":{\"S\":\"b\"}}],\"Count\":2,"
|
||||
+ "\"ScannedCount\":5,\"LastEvaluatedKey\":{\"pk\":{\"S\":\"b\"}}}");
|
||||
|
||||
ScanPage page = backend.scan(SCOPE, "orders", null, null, null, null, 2, json("{\"pk\":{\"S\":\"0\"}}"));
|
||||
|
||||
assertEquals(List.of(json("{\"pk\":{\"S\":\"a\"}}"), json("{\"pk\":{\"S\":\"b\"}}")), page.items());
|
||||
assertEquals(5, page.scannedCount());
|
||||
assertEquals(json("{\"pk\":{\"S\":\"b\"}}"), page.lastEvaluatedKey());
|
||||
assertEquals(json("{\"TableName\":\"orders\",\"Limit\":2,\"ExclusiveStartKey\":{\"pk\":{\"S\":\"0\"}}}"),
|
||||
sent("Scan"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resourcesListsTablesOfKnownRegions() throws Exception {
|
||||
tags.putForAccount(ACCOUNT, REGION + "/orders", Map.of("env", "dev"));
|
||||
tags.putForAccount(ACCOUNT, "us-east-1/users", Map.of());
|
||||
when(client.send(any(), eq(Api.DYNAMODB), eq("ListTables"), any())).thenAnswer(invocation -> {
|
||||
Scope scope = invocation.getArgument(0);
|
||||
JsonNode body = invocation.getArgument(3);
|
||||
String page;
|
||||
if ("us-east-1".equals(scope.region())) {
|
||||
page = "{\"TableNames\":[\"users\"]}";
|
||||
} else if (body.has("ExclusiveStartTableName")) {
|
||||
page = "{\"TableNames\":[\"direct\"]}";
|
||||
} else {
|
||||
page = "{\"TableNames\":[\"orders\"],\"LastEvaluatedTableName\":\"orders\"}";
|
||||
}
|
||||
return new Reply(200, json(page), Map.of());
|
||||
});
|
||||
|
||||
List<ExplorerResource> resources = backend.resources(ACCOUNT);
|
||||
|
||||
Map<String, ExplorerResource> byArn = resources.stream()
|
||||
.collect(Collectors.toMap(ExplorerResource::arn, resource -> resource));
|
||||
assertEquals(Set.of(ORDERS_ARN, PUBLIC + "table/direct", "arn:aws:dynamodb:us-east-1:123456789012:table/users"),
|
||||
byArn.keySet());
|
||||
ExplorerResource orders = byArn.get(ORDERS_ARN);
|
||||
assertEquals("dynamodb:table", orders.resourceType());
|
||||
assertEquals(REGION, orders.region());
|
||||
assertEquals(ACCOUNT, orders.owningAccountId());
|
||||
assertEquals(Map.of("env", "dev"), orders.tags());
|
||||
assertEquals(Map.of(), byArn.get(PUBLIC + "table/direct").tags());
|
||||
assertTrue(sentBodies(Api.DYNAMODB, "ListTables").contains(json("{\"ExclusiveStartTableName\":\"orders\"}")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetRefusedWith409() {
|
||||
AwsException error = assertThrows(AwsException.class, backend::checkReset);
|
||||
|
||||
assertEquals("UnsupportedOperation", error.getErrorCode());
|
||||
assertEquals(409, error.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void startRetriesConnectionFailuresThenSucceeds() throws Exception {
|
||||
Scope probe = new Scope("000000000000", "us-east-1");
|
||||
when(client.send(eq(probe), eq(Api.DYNAMODB), eq("ListTables"), any(), any()))
|
||||
.thenThrow(new ConnectException("refused"))
|
||||
.thenReturn(new Reply(200, json("{\"TableNames\":[]}"), Map.of()));
|
||||
|
||||
backend.start();
|
||||
|
||||
verify(client, times(2)).send(eq(probe), eq(Api.DYNAMODB), eq("ListTables"), eq(json("{\"Limit\":1}")), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void startRetriesAConnectionClosedWithoutAnswer() throws Exception {
|
||||
Scope probe = new Scope("000000000000", "us-east-1");
|
||||
when(client.send(eq(probe), eq(Api.DYNAMODB), eq("ListTables"), any(), any()))
|
||||
.thenThrow(new IOException("HTTP/1.1 header parser received no bytes"))
|
||||
.thenReturn(new Reply(200, json("{\"TableNames\":[]}"), Map.of()));
|
||||
|
||||
backend.start();
|
||||
|
||||
verify(client, times(2)).send(eq(probe), eq(Api.DYNAMODB), eq("ListTables"), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void startCapsEachProbeAtTheRemainingBudget() throws Exception {
|
||||
ArgumentCaptor<Duration> budget = ArgumentCaptor.forClass(Duration.class);
|
||||
when(client.send(any(), any(), any(), any(), budget.capture()))
|
||||
.thenReturn(new Reply(200, json("{\"TableNames\":[]}"), Map.of()));
|
||||
|
||||
backend.start();
|
||||
|
||||
assertTrue(budget.getValue().isPositive());
|
||||
assertTrue(budget.getValue().compareTo(Duration.ofSeconds(5)) <= 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void startFailsWhenBudgetExpires() throws Exception {
|
||||
backend = new DynamoDbLocalBackend(client, tags, mapper, Duration.ZERO);
|
||||
when(client.send(any(), any(), any(), any(), any())).thenThrow(new ConnectException("refused"));
|
||||
|
||||
IllegalStateException error = assertThrows(IllegalStateException.class, backend::start);
|
||||
|
||||
assertEquals("DynamoDB Local at http://local:8000 is not reachable after 0s", error.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void startFailsOnNon2xx() throws Exception {
|
||||
when(client.send(any(), any(), any(), any(), any())).thenReturn(new Reply(500, json("{\"message\":\"x\"}"), Map.of()));
|
||||
|
||||
IllegalStateException error = assertThrows(IllegalStateException.class, backend::start);
|
||||
|
||||
assertEquals("DynamoDB Local at http://local:8000 answered ListTables with status 500: {\"message\":\"x\"}",
|
||||
error.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void validatedEndpointMissing() {
|
||||
for (Optional<String> missing : List.of(Optional.<String>empty(), Optional.of(" "))) {
|
||||
IllegalStateException error = assertThrows(IllegalStateException.class,
|
||||
() -> DynamoDbLocalBackend.validatedEndpoint(missing));
|
||||
|
||||
assertEquals("floci.services.dynamodb.local-endpoint is required when floci.services.dynamodb.backend "
|
||||
+ "is local", error.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void validatedEndpointFtpScheme() {
|
||||
IllegalStateException error = assertThrows(IllegalStateException.class,
|
||||
() -> DynamoDbLocalBackend.validatedEndpoint(Optional.of("ftp://localhost:8000")));
|
||||
|
||||
assertTrue(error.getMessage().contains("ftp://localhost:8000"), error.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void validatedEndpointAwsHost() {
|
||||
IllegalStateException error = assertThrows(IllegalStateException.class,
|
||||
() -> DynamoDbLocalBackend.validatedEndpoint(Optional.of("https://dynamodb.us-east-1.amazonaws.com")));
|
||||
|
||||
assertTrue(error.getMessage().endsWith("must point at DynamoDB Local, not an AWS endpoint"),
|
||||
error.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void validatedEndpointAwsHostInAnyPartitionOrWithTrailingDot() {
|
||||
for (String endpoint : List.of("https://dynamodb.us-east-1.amazonaws.com.",
|
||||
"https://dynamodb.cn-north-1.amazonaws.com.cn", "https://dynamodb.eu-isoe-west-1.cloud.adc-e.uk")) {
|
||||
assertThrows(IllegalStateException.class,
|
||||
() -> DynamoDbLocalBackend.validatedEndpoint(Optional.of(endpoint)), endpoint);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void validatedEndpointUserInfoRejected() {
|
||||
assertThrows(IllegalStateException.class,
|
||||
() -> DynamoDbLocalBackend.validatedEndpoint(Optional.of("http://user:secret@localhost:8000")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void validatedEndpointValid() {
|
||||
assertEquals(URI.create("http://localhost:8000"),
|
||||
DynamoDbLocalBackend.validatedEndpoint(Optional.of("http://localhost:8000")));
|
||||
}
|
||||
}
|
||||
+247
@@ -0,0 +1,247 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb.backend;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.sun.net.httpserver.Headers;
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Api;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Reply;
|
||||
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Scope;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.net.ConnectException;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpTimeoutException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/** The signed HTTP client that forwards DynamoDB wire calls to an external DynamoDB Local. */
|
||||
class DynamoDbLocalClientTest {
|
||||
|
||||
private static final Scope SCOPE = new Scope("123456789012", "eu-west-1");
|
||||
private static final Pattern AUTHORIZATION = Pattern.compile(
|
||||
"AWS4-HMAC-SHA256 Credential=([^/]+)/(\\d{8})/([^/]+)/dynamodb/aws4_request, "
|
||||
+ "SignedHeaders=content-type;host;x-amz-date;x-amz-target, Signature=([0-9a-f]{64})");
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private final AtomicReference<Received> received = new AtomicReference<>();
|
||||
private final AtomicInteger hits = new AtomicInteger();
|
||||
private HttpServer server;
|
||||
private DynamoDbLocalClient client;
|
||||
|
||||
private record Received(String path, Headers headers, byte[] body) {
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
private interface Responder {
|
||||
void respond(HttpExchange exchange) throws Exception;
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
if (client != null) {
|
||||
client.close();
|
||||
}
|
||||
if (server != null) {
|
||||
server.stop(0);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void signsAndForwardsExactBody() throws Exception {
|
||||
start(exchange -> reply(exchange, 200, "{}"));
|
||||
ObjectNode body = (ObjectNode) mapper.readTree("""
|
||||
{"TableName":"orders","Item":{
|
||||
"pk":{"S":"a"},
|
||||
"blob":{"B":"AAEC"},
|
||||
"blobs":{"BS":["AAEC","AwQF"]},
|
||||
"numbers":{"NS":["1","2.5"]},
|
||||
"big":{"N":"12345678901234567890123456789012345678"},
|
||||
"nested":{"M":{"inner":{"B":"BgcI"}}}}}
|
||||
""");
|
||||
|
||||
Reply result = client.send(SCOPE, Api.DYNAMODB, "PutItem", body);
|
||||
|
||||
assertEquals(200, result.status());
|
||||
Received request = received.get();
|
||||
assertArrayEquals(mapper.writeValueAsBytes(body), request.body());
|
||||
assertEquals("DynamoDB_20120810.PutItem", request.headers().getFirst("X-Amz-Target"));
|
||||
assertEquals("application/x-amz-json-1.0", request.headers().getFirst("Content-Type"));
|
||||
String amzDate = request.headers().getFirst("X-Amz-Date");
|
||||
assertNotNull(amzDate);
|
||||
String date = amzDate.substring(0, 8);
|
||||
String authorization = request.headers().getFirst("Authorization");
|
||||
assertTrue(authorization.contains(
|
||||
"Credential=floci123456789012/" + date + "/eu-west-1/dynamodb/aws4_request"),
|
||||
authorization);
|
||||
Matcher matcher = AUTHORIZATION.matcher(authorization);
|
||||
assertTrue(matcher.matches(), authorization);
|
||||
assertEquals(expectedSignature(request, date), matcher.group(4));
|
||||
}
|
||||
|
||||
@Test
|
||||
void streamsTargetPrefix() throws Exception {
|
||||
start(exchange -> reply(exchange, 200, "{}"));
|
||||
|
||||
client.send(SCOPE, Api.DYNAMODB_STREAMS, "GetRecords", mapper.createObjectNode());
|
||||
|
||||
assertEquals("DynamoDBStreams_20120810.GetRecords", received.get().headers().getFirst("X-Amz-Target"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void errorBodyPreserved() throws Exception {
|
||||
String error = "{\"__type\":\"com.amazonaws.dynamodb.v20120810#TransactionCanceledException\","
|
||||
+ "\"message\":\"x\",\"CancellationReasons\":[{\"Code\":\"ConditionalCheckFailed\"}]}";
|
||||
start(exchange -> reply(exchange, 400, error));
|
||||
|
||||
Reply result = client.send(SCOPE, Api.DYNAMODB, "TransactWriteItems", mapper.createObjectNode());
|
||||
|
||||
assertEquals(400, result.status());
|
||||
assertEquals(mapper.readTree(error), result.body());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownOperationPassesThrough() throws Exception {
|
||||
start(exchange -> reply(exchange, 200, "{}"));
|
||||
|
||||
client.send(SCOPE, Api.DYNAMODB, "SomeFutureAction", mapper.createObjectNode());
|
||||
|
||||
assertEquals("DynamoDB_20120810.SomeFutureAction", received.get().headers().getFirst("X-Amz-Target"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullBodySendsEmptyObject() throws Exception {
|
||||
start(exchange -> reply(exchange, 200, "{}"));
|
||||
|
||||
client.send(SCOPE, Api.DYNAMODB, "ListTables", null);
|
||||
|
||||
assertEquals("{}", new String(received.get().body(), StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyResponseBodyIsNull() throws Exception {
|
||||
start(exchange -> reply(exchange, 200, ""));
|
||||
|
||||
Reply result = client.send(SCOPE, Api.DYNAMODB, "ListTables", mapper.createObjectNode());
|
||||
|
||||
assertEquals(200, result.status());
|
||||
assertNull(result.body());
|
||||
}
|
||||
|
||||
@Test
|
||||
void connectionRefused() throws Exception {
|
||||
int port;
|
||||
try (ServerSocket socket = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1"))) {
|
||||
port = socket.getLocalPort();
|
||||
}
|
||||
client = new DynamoDbLocalClient(URI.create("http://127.0.0.1:" + port),
|
||||
Duration.ofSeconds(2), Duration.ofSeconds(2), mapper);
|
||||
|
||||
assertThrows(ConnectException.class,
|
||||
() -> client.send(SCOPE, Api.DYNAMODB, "ListTables", mapper.createObjectNode()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void timedOutRequestIsSentOnce() throws Exception {
|
||||
start(exchange -> {
|
||||
hits.incrementAndGet();
|
||||
Thread.sleep(2000);
|
||||
reply(exchange, 200, "{}");
|
||||
}, Duration.ofMillis(200));
|
||||
|
||||
assertThrows(HttpTimeoutException.class,
|
||||
() -> client.send(SCOPE, Api.DYNAMODB, "ListTables", mapper.createObjectNode()));
|
||||
Thread.sleep(500);
|
||||
assertEquals(1, hits.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aShorterBudgetCutsTheRequestTimeout() throws Exception {
|
||||
start(exchange -> {
|
||||
Thread.sleep(2000);
|
||||
reply(exchange, 200, "{}");
|
||||
}, Duration.ofSeconds(5));
|
||||
|
||||
assertThrows(HttpTimeoutException.class, () -> client.send(SCOPE, Api.DYNAMODB, "ListTables",
|
||||
mapper.createObjectNode(), Duration.ofMillis(200)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLongerBudgetKeepsTheRequestTimeout() throws Exception {
|
||||
start(exchange -> {
|
||||
Thread.sleep(2000);
|
||||
reply(exchange, 200, "{}");
|
||||
}, Duration.ofMillis(200));
|
||||
|
||||
assertThrows(HttpTimeoutException.class, () -> client.send(SCOPE, Api.DYNAMODB, "ListTables",
|
||||
mapper.createObjectNode(), Duration.ofSeconds(5)));
|
||||
}
|
||||
|
||||
private void start(Responder responder) throws IOException {
|
||||
start(responder, Duration.ofSeconds(5));
|
||||
}
|
||||
|
||||
private void start(Responder responder, Duration requestTimeout) throws IOException {
|
||||
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
server.createContext("/", exchange -> {
|
||||
try (exchange) {
|
||||
received.set(new Received(exchange.getRequestURI().getRawPath(),
|
||||
exchange.getRequestHeaders(), exchange.getRequestBody().readAllBytes()));
|
||||
responder.respond(exchange);
|
||||
} catch (Exception e) {
|
||||
throw new IOException(e);
|
||||
}
|
||||
});
|
||||
server.start();
|
||||
URI endpoint = URI.create("http://127.0.0.1:" + server.getAddress().getPort());
|
||||
client = new DynamoDbLocalClient(endpoint, Duration.ofSeconds(2), requestTimeout, mapper);
|
||||
}
|
||||
|
||||
private static void reply(HttpExchange exchange, int status, String body) throws IOException {
|
||||
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
|
||||
exchange.getResponseHeaders().set("Content-Type", "application/x-amz-json-1.0");
|
||||
exchange.sendResponseHeaders(status, bytes.length == 0 ? -1 : bytes.length);
|
||||
if (bytes.length > 0) {
|
||||
try (OutputStream out = exchange.getResponseBody()) {
|
||||
out.write(bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String expectedSignature(Received request, String date) throws Exception {
|
||||
Headers headers = request.headers();
|
||||
String amzDate = headers.getFirst("X-Amz-Date");
|
||||
String canonical = "POST\n" + request.path() + "\n\n"
|
||||
+ "content-type:" + headers.getFirst("Content-Type") + "\n"
|
||||
+ "host:" + headers.getFirst("Host") + "\n"
|
||||
+ "x-amz-date:" + amzDate + "\n"
|
||||
+ "x-amz-target:" + headers.getFirst("X-Amz-Target") + "\n\n"
|
||||
+ "content-type;host;x-amz-date;x-amz-target\n"
|
||||
+ SigV4RequestValidator.sha256Hex(request.body());
|
||||
String credentialScope = date + "/eu-west-1/dynamodb/aws4_request";
|
||||
String toSign = "AWS4-HMAC-SHA256\n" + amzDate + "\n" + credentialScope + "\n"
|
||||
+ SigV4RequestValidator.sha256Hex(canonical);
|
||||
byte[] key = SigV4RequestValidator.deriveSigningKey("floci", date, "eu-west-1", "dynamodb");
|
||||
return SigV4RequestValidator.hexEncode(SigV4RequestValidator.hmacSha256(key, toSign));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user