fix(dynamodb): support legacy table discovery and batch cleanup (#5986)

Signed-off-by: Andre Kurait <akurait@amazon.com>
This commit is contained in:
Andre Kurait authored and GitHub committed 2026-10-19 13:30:04 -04:00
1 parent e5a206554f
commit 0a37ea830b
27 files changed
+1003 -24

No files matched your search

@@ -111,6 +111,6 @@ class AwsQueryServiceResolverTest {
private static ServiceDescriptor descriptor(String service, ServiceProtocol protocol) {
return new ServiceDescriptor(service, service, true, true, service, "memory", 0L,
null, protocol, Set.of(protocol), Set.of(), Set.of(service), Set.of(), Set.of());
null, protocol, Set.of(protocol), Set.of(), Set.of(service), Set.of(), Set.of(), Set.of());
}
}
@@ -63,6 +63,7 @@ class IamConditionContextResolverTest {
private RequestContext requestContext;
private EmulatorConfig config;
private IamConditionContextResolver resolver;
private ResolvedServiceCatalog serviceCatalog;
@SuppressWarnings("unchecked")
@BeforeEach
@@ -89,9 +90,16 @@ class IamConditionContextResolverTest {
requestContext.setRegion("us-east-1");
config = mock(EmulatorConfig.class);
when(config.defaultRegion()).thenReturn("us-east-1");
serviceCatalog = mock(ResolvedServiceCatalog.class);
ServiceDescriptor dynamo = new ServiceDescriptor("dynamodb", "dynamodb", true, true,
null, null, 0L, null, ServiceProtocol.JSON, Set.of(ServiceProtocol.JSON),
Set.of("DynamoDB_20111205."), Set.of("dynamodb"), Set.of(), Set.of(),
Set.of("DynamoDB_20111205."));
ServiceCatalog catalog = new ServiceCatalog(List.of(dynamo));
when(serviceCatalog.matchTarget(any())).thenAnswer(call -> catalog.matchTarget(call.getArgument(0)));
resolver = new IamConditionContextResolver(
dynamoDbFacadeInstance, ec2ServiceInstance, s3ServiceInstance, logsServiceInstance, requestContext, config,
null);
null, serviceCatalog);
}
@Test
@@ -360,7 +368,7 @@ class IamConditionContextResolverTest {
@SuppressWarnings("unchecked")
private IamConditionContextResolver resolverAt(Instant now) {
return new IamConditionContextResolver(mock(Instance.class), mock(Instance.class), mock(Instance.class),
mock(Instance.class), requestContext, config, null, Clock.fixed(now, ZoneOffset.UTC));
mock(Instance.class), requestContext, config, null, serviceCatalog, Clock.fixed(now, ZoneOffset.UTC));
}
@Test
@@ -471,6 +479,47 @@ class IamConditionContextResolverTest {
}
}
@Test
void legacyQueryConditionsRequireTheLegacyJsonTarget() {
ContainerRequestContext request = mock(ContainerRequestContext.class);
when(request.getProperty("floci.bufferedJsonBody")).thenReturn(json("""
{"TableName":"FgacTable","HashKeyValue":{"S":"USER_bob"},
"RangeKeyCondition":{"ComparisonOperator":"EQ","AttributeValueList":[{"S":"private"}]},
"Count":true,"AttributesToGet":["secret"],
"KeyConditions":{"PK":{"ComparisonOperator":"EQ","AttributeValueList":[{"S":"USER_alice"}]}}}
"""));
when(request.getMediaType()).thenReturn(MediaType.valueOf("application/x-amz-json-1.0"));
when(request.getHeaderString("X-Amz-Target")).thenReturn("DynamoDB_20111205.Query");
TableDefinition table = fgacTable();
table.setKeySchema(List.of(new KeySchemaElement("PK", "HASH"), new KeySchemaElement("SK", "RANGE")));
when(dynamoDbService.findTable("FgacTable", "us-east-1")).thenReturn(Optional.of(table));
Map<String, List<String>> legacy = resolver.resolve("dynamodb", "dynamodb:Query", request);
assertEquals(List.of("USER_bob"), legacy.get("dynamodb:LeadingKeys"));
assertEquals(Set.of("PK", "SK", "secret"), new HashSet<>(legacy.get("dynamodb:Attributes")));
assertEquals(List.of("COUNT"), legacy.get("dynamodb:Select"));
when(request.getHeaderString("X-Amz-Target")).thenReturn("DynamoDB_20120810.Query");
Map<String, List<String>> modern = resolver.resolve("dynamodb", "dynamodb:Query", request);
assertEquals(List.of("USER_alice"), modern.get("dynamodb:LeadingKeys"));
assertFalse(modern.containsKey("dynamodb:Select"));
}
@Test
void legacyBatchDeleteCannotHidePartitionOrAttributeNames() {
ContainerRequestContext request = mock(ContainerRequestContext.class);
when(request.getProperty("floci.bufferedJsonBody")).thenReturn(json("""
{"RequestItems":{"FgacTable":[{"DeleteRequest":{"Key":{
"HashKeyElement":{"S":"USER_bob"},"RangeKeyElement":{"S":"private"}}}}]}}
"""));
when(request.getMediaType()).thenReturn(MediaType.valueOf("application/x-amz-json-1.0"));
when(request.getHeaderString("X-Amz-Target")).thenReturn("DynamoDB_20111205.BatchWriteItem");
TableDefinition table = fgacTable();
table.setKeySchema(List.of(new KeySchemaElement("PK", "HASH"), new KeySchemaElement("SK", "RANGE")));
when(dynamoDbService.findTable("FgacTable", "us-east-1")).thenReturn(Optional.of(table));
Map<String, List<String>> conditions = resolver.resolve("dynamodb", "dynamodb:BatchWriteItem", request);
assertEquals(List.of("USER_bob"), conditions.get("dynamodb:LeadingKeys"));
assertEquals(Set.of("PK", "SK"), new HashSet<>(conditions.get("dynamodb:Attributes")));
}
@Test
void returnsNullWhenNoBodyWasBuffered() {
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
@@ -270,7 +270,7 @@ class IamEnforcementFilterTest {
private static ServiceDescriptor pricingDescriptor() {
return new ServiceDescriptor("pricing", "pricing", true, true, null, null, 5000L, null,
ServiceProtocol.JSON, Set.of(ServiceProtocol.JSON), Set.of("AWSPriceListService."),
Set.of("pricing", "api.pricing"), Set.of(), Set.of());
Set.of("pricing", "api.pricing"), Set.of(), Set.of(), Set.of());
}
@Test
@@ -433,7 +433,7 @@ class IamEnforcementFilterTest {
private static ServiceDescriptor dynamoDbDescriptor() {
return new ServiceDescriptor("dynamodb", "dynamodb", true, true, "dynamodb", "memory", 0L, null,
ServiceProtocol.JSON, Set.of(ServiceProtocol.JSON), Set.of("DynamoDB_20120810."),
Set.of("dynamodb"), Set.of(), Set.of());
Set.of("dynamodb"), Set.of(), Set.of(), Set.of());
}
private static ResourceInfo resourceInfo(Class<?> resourceClass) {
@@ -446,7 +446,7 @@ class IamEnforcementFilterTest {
Set<String> scopes, Class<?> resourceClass) {
Set<Class<?>> resourceClasses = resourceClass == null ? Set.of() : Set.of(resourceClass);
return new ServiceDescriptor(service, service, true, true, service, "memory", 0L,
null, protocol, Set.of(protocol), Set.of(), scopes, Set.of(), resourceClasses);
null, protocol, Set.of(protocol), Set.of(), scopes, Set.of(), resourceClasses, Set.of());
}
@Test
@@ -50,6 +50,8 @@ class ServiceCatalogRoutingIntegrationTest {
assertEquals("sqs", catalog.byCborSdkServiceId("AmazonSQS").orElseThrow().externalKey());
assertEquals("sns", catalog.byCborSdkServiceId("SNS_20100331").orElseThrow().externalKey());
assertEquals("states", catalog.byCborSdkServiceId("AWSStepFunctions").orElseThrow().externalKey());
assertTrue(catalog.byCborSdkServiceId("DynamoDB_20111205").isEmpty());
assertEquals("DescribeTable", catalog.matchTarget("DynamoDB_20111205.DescribeTable").orElseThrow().action());
}
@Test
@@ -6,6 +6,7 @@ import java.util.List;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class ServiceCatalogTest {
@@ -35,8 +36,22 @@ class ServiceCatalogTest {
assertTrue(catalog.matchPlainJsonTarget("Example.Specific.Read").isEmpty());
}
@Test
void jsonOnlyPrefixesCannotSelectCborAndAreRecognizedByTheirDescriptor() {
ServiceDescriptor service = new ServiceDescriptor("example", "example", true, true,
null, null, 0L, null, ServiceProtocol.JSON, Set.of(ServiceProtocol.JSON, ServiceProtocol.CBOR),
Set.of("LegacyExample.", "Example."), Set.of("example"), Set.of(), Set.of(),
Set.of("LegacyExample."));
ServiceCatalog catalog = new ServiceCatalog(List.of(service));
assertTrue(catalog.matchTarget("LegacyExample.Read").orElseThrow().jsonOnly());
assertFalse(catalog.matchTarget("Example.Read").orElseThrow().jsonOnly());
assertTrue(catalog.byCborSdkServiceId("LegacyExample").isEmpty());
assertEquals(service, catalog.byCborSdkServiceId("Example").orElseThrow());
}
private static ServiceDescriptor descriptor(String name, Set<String> prefixes, Set<ServiceProtocol> protocols) {
return new ServiceDescriptor(name, name, true, true, null, null, 0L, null,
ServiceProtocol.JSON, protocols, prefixes, Set.of(name), Set.of(), Set.of());
ServiceProtocol.JSON, protocols, prefixes, Set.of(name), Set.of(), Set.of(), Set.of());
}
}
@@ -46,7 +46,7 @@ class PersistentPathValidatorTest {
private static ServiceDescriptor descriptor(String key, boolean enabled, String storageKey, String mode) {
return new ServiceDescriptor(key, key, enabled, true, storageKey, mode, 0L,
null, ServiceProtocol.REST_XML, Set.of(ServiceProtocol.REST_XML),
Set.of(), Set.of(), Set.of(), Set.of());
Set.of(), Set.of(), Set.of(), Set.of(), Set.of());
}
@Test
@@ -28,6 +28,19 @@ class DynamoDbCborIntegrationTest {
private static final ObjectMapper CBOR_MAPPER = new ObjectMapper(new CBORFactory());
private static final ObjectMapper JSON_MAPPER = new ObjectMapper();
@Test
void legacyDynamoDbTargetDoesNotEnterModernCborHandling() throws Exception {
byte[] body = CBOR_MAPPER.writeValueAsBytes(JSON_MAPPER.readTree("{\"TableName\":\"CborTable\"}"));
for (String contentType : new String[]{"application/cbor", "application/x-amz-cbor-1.1"}) {
byte[] result = given().contentType(contentType).accept(contentType)
.header("X-Amz-Target", "DynamoDB_20111205.DescribeTable").body(body)
.post("/").then().statusCode(404).extract().asByteArray();
assertThat(CBOR_MAPPER.readTree(result).path("__type").asText(), containsString("UnknownOperation"));
}
given().contentType("application/cbor").body(body)
.post("/service/DynamoDB_20111205/operation/DescribeTable").then().statusCode(404);
}
@Test
@Order(1)
void createTableViaCbor() throws Exception {
@@ -38,6 +38,21 @@ class DynamoDbConditionKeysTest {
}
}
@Test
void legacyPartitionValuesRemainExplicitWhenTableMetadataIsUnavailable() {
DynamoDbConditionKeys.Result query = DynamoDbConditionKeys.extractLegacy("dynamodb:Query",
json("{\"TableName\":\"missing\",\"HashKeyValue\":{\"S\":\"USER_bob\"}}"), null);
assertEquals(List.of("USER_bob"), query.leadingKeys());
assertTrue(query.attributes().isEmpty());
DynamoDbConditionKeys.Result deletes = DynamoDbConditionKeys.extractLegacy("dynamodb:BatchWriteItem",
json("""
{"RequestItems":{"missing":[{"DeleteRequest":{"Key":{
"HashKeyElement":{"S":"USER_bob"},"RangeKeyElement":{"S":"profile"}}}}]}}
"""), null);
assertEquals(List.of("USER_bob"), deletes.leadingKeys());
assertTrue(deletes.attributes().isEmpty());
}
@Test
void getItemExposesTheKeyValueAndTheKeyAttributeNames() {
DynamoDbConditionKeys.Result result = DynamoDbConditionKeys.extract(
@@ -0,0 +1,77 @@
package io.github.hectorvent.floci.services.dynamodb;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.zip.CRC32;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
@QuarkusTest
class DynamoDbLegacyIntegrationTest {
@BeforeAll
static void configureJson() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void missingTableHasAwsErrorAndCrcInsteadOfAnUnrecognizedTarget() {
Response response = call("20111205", "DescribeTable", "{\"TableName\":\"absent-" + UUID.randomUUID() + "\"}");
response.then().statusCode(400).body("__type",
equalTo("com.amazonaws.dynamodb.v20111205#ResourceNotFoundException"));
CRC32 crc = new CRC32();
crc.update(response.asString().getBytes(StandardCharsets.UTF_8));
assertEquals(Long.toUnsignedString(crc.getValue()), response.header("x-amz-crc32"));
given().header("X-Amz-Target", "DynamoDB_20111205.DescribeTable")
.contentType("application/json").body("{\"TableName\":\"absent\"}")
.post("/").then().statusCode(404);
}
@Test
void legacyAndModernTableMetadataShareActualStorage() {
String name = "legacy-" + UUID.randomUUID();
call("20120810", "CreateTable", """
{"TableName":"%s","KeySchema":[{"AttributeName":"pk","KeyType":"HASH"}],
"AttributeDefinitions":[{"AttributeName":"pk","AttributeType":"S"}],
"BillingMode":"PAY_PER_REQUEST"}
""".formatted(name)).then().statusCode(200);
try {
call("20111205", "DescribeTable", "{\"TableName\":\"" + name + "\"}").then().statusCode(200)
.body("Table.TableName", equalTo(name))
.body("Table.KeySchema.HashKeyElement.AttributeName", equalTo("pk"))
.body("Table.KeySchema.HashKeyElement.AttributeType", equalTo("S"))
.body("Table.KeySchema.RangeKeyElement", nullValue());
call("20120810", "DescribeTable", "{\"TableName\":\"" + name + "\"}").then().statusCode(200)
.body("Table.KeySchema[0].KeyType", equalTo("HASH"))
.body("Table.AttributeDefinitions[0].AttributeName", equalTo("pk"));
call("20111205", "GetItem", "{\"TableName\":\"" + name + "\"}").then().statusCode(400)
.body("__type", equalTo("com.amazonaws.dynamodb.v20111205#UnknownOperationException"));
} finally {
call("20120810", "DeleteTable", "{\"TableName\":\"" + name + "\"}").then().statusCode(200);
}
}
@Test
void adapterValidationErrorsUseLegacyNamespaceAndCorrectCrc() {
Response response = call("20111205", "Query", "{}");
response.then().statusCode(400)
.body("__type", equalTo("com.amazon.coral.validate#ValidationException"));
CRC32 crc = new CRC32();
crc.update(response.asString().getBytes(StandardCharsets.UTF_8));
assertEquals(Long.toUnsignedString(crc.getValue()), response.header("x-amz-crc32"));
call("20120810", "Query", "{}").then().statusCode(400)
.body("__type", not(containsString("v20111205")));
}
private static Response call(String version, String action, String body) {
return given().header("X-Amz-Target", "DynamoDB_" + version + "." + action)
.contentType("application/x-amz-json-1.0").body(body).post("/");
}
}
@@ -0,0 +1,179 @@
package io.github.hectorvent.floci.services.dynamodb;
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.services.dynamodb.backend.DynamoDbOperations;
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 org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
class DynamoDbLegacyProtocolTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final Scope SCOPE = new Scope("123456789012", "eu-west-1");
private static final String TABLE = """
{"Table":{"TableName":"metrics","TableStatus":"ACTIVE",
"KeySchema":[{"AttributeName":"id-type","KeyType":"HASH"},{"AttributeName":"range","KeyType":"RANGE"}],
"AttributeDefinitions":[{"AttributeName":"id-type","AttributeType":"S"},
{"AttributeName":"range","AttributeType":"N"}]}}
""";
@Test
void describesActualSchemaAndPreservesBackendErrors() throws Exception {
Reply described = new DynamoDbLegacyProtocol(call -> reply(TABLE), SCOPE)
.execute("DescribeTable", json("{\"TableName\":\"metrics\"}"));
assertEquals(json("""
{"HashKeyElement":{"AttributeName":"id-type","AttributeType":"S"},
"RangeKeyElement":{"AttributeName":"range","AttributeType":"N"}}
"""), described.body().path("Table").path("KeySchema"));
assertEquals("metrics", described.body().path("Table").path("TableName").asText());
Reply denied = new Reply(400, json("{\"__type\":\"ResourceNotFoundException\"}"),
Map.of("x-test", List.of("kept")));
assertSame(denied, new DynamoDbLegacyProtocol(call -> denied, SCOPE)
.execute("DescribeTable", json("{\"TableName\":\"absent\"}")));
}
@Test
void translatesQueryConditionsPaginationAndCapacityInOneScope() throws Exception {
List<Call> calls = new ArrayList<>();
DynamoDbOperations operations = call -> {
calls.add(call);
return reply("DescribeTable".equals(call.action()) ? TABLE : """
{"Items":[{"range":{"N":"3"}}],"Count":1,
"LastEvaluatedKey":{"id-type":{"S":"domain_q"},"range":{"N":"3"}},
"ConsumedCapacity":{"TableName":"metrics","CapacityUnits":0.5}}
""");
};
JsonNode request = json("""
{"TableName":"metrics","HashKeyValue":{"S":"domain_q"},
"RangeKeyCondition":{"ComparisonOperator":"BETWEEN","AttributeValueList":[{"N":"2"},{"N":"9"}]},
"ExclusiveStartKey":{"HashKeyElement":{"S":"domain_q"},"RangeKeyElement":{"N":"2"}},
"Limit":1,"ConsistentRead":true,"ScanIndexForward":false,"AttributesToGet":["range"]}
""");
JsonNode original = request.deepCopy();
Reply reply = new DynamoDbLegacyProtocol(operations, SCOPE).execute("Query", request);
assertEquals(original, request);
assertEquals(List.of("DescribeTable", "Query"), calls.stream().map(Call::action).toList());
assertTrue(calls.stream().allMatch(call -> call.scope().equals(SCOPE)));
assertEquals(json("""
{"id-type":{"ComparisonOperator":"EQ","AttributeValueList":[{"S":"domain_q"}]},
"range":{"ComparisonOperator":"BETWEEN","AttributeValueList":[{"N":"2"},{"N":"9"}]}}
"""), calls.getLast().body().path("KeyConditions"));
assertEquals(json("{\"id-type\":{\"S\":\"domain_q\"},\"range\":{\"N\":\"2\"}}"),
calls.getLast().body().path("ExclusiveStartKey"));
assertEquals(1, calls.getLast().body().path("Limit").asInt());
assertTrue(calls.getLast().body().path("ConsistentRead").asBoolean());
assertFalse(calls.getLast().body().path("ScanIndexForward").asBoolean());
assertEquals(json("[\"range\"]"), calls.getLast().body().path("AttributesToGet"));
assertEquals(json("{\"HashKeyElement\":{\"S\":\"domain_q\"},\"RangeKeyElement\":{\"N\":\"3\"}}"),
reply.body().path("LastEvaluatedKey"));
assertEquals(0.5, reply.body().path("ConsumedCapacityUnits").asDouble());
assertEquals(1, reply.body().path("Count").asInt());
}
@Test
void countUsesBackendCountAndOmitsAbsentContinuation() throws Exception {
List<Call> calls = new ArrayList<>();
DynamoDbLegacyProtocol protocol = new DynamoDbLegacyProtocol(call -> {
calls.add(call);
return reply("DescribeTable".equals(call.action()) ? TABLE : """
{"Count":7,"LastEvaluatedKey":{},"ConsumedCapacity":{"CapacityUnits":2.0}}
""");
}, SCOPE);
Reply reply = protocol.execute("Query",
json("{\"TableName\":\"metrics\",\"HashKeyValue\":{\"S\":\"domain_q\"},\"Count\":true}"));
assertEquals("COUNT", calls.getLast().body().path("Select").asText());
assertEquals(7, reply.body().path("Count").asInt());
assertFalse(reply.body().has("Items"));
assertFalse(reply.body().has("LastEvaluatedKey"));
}
@Test
void batchRetriesKeepLegacyKeysAndRealPerTableCapacity() throws Exception {
List<Call> calls = new ArrayList<>();
DynamoDbOperations operations = call -> {
calls.add(call);
return reply("DescribeTable".equals(call.action()) ? TABLE : """
{"UnprocessedItems":{"metrics":[
{"DeleteRequest":{"Key":{"id-type":{"S":"domain_q"},"range":{"N":"3"}}}},
{"PutRequest":{"Item":{"id-type":{"S":"domain_d"},"range":{"N":"4"}}}}]},
"ConsumedCapacity":[{"TableName":"metrics","CapacityUnits":2.0}]}
""");
};
JsonNode request = json("""
{"RequestItems":{"metrics":[
{"DeleteRequest":{"Key":{"HashKeyElement":{"S":"domain_q"},"RangeKeyElement":{"N":"3"}}}},
{"PutRequest":{"Item":{"id-type":{"S":"domain_d"},"range":{"N":"4"}}}}]}}
""");
JsonNode original = request.deepCopy();
Reply reply = new DynamoDbLegacyProtocol(operations, SCOPE).execute("BatchWriteItem", request);
assertEquals(original, request);
assertEquals(2, calls.size());
assertTrue(calls.stream().allMatch(call -> call.scope().equals(SCOPE)));
assertEquals(json("{\"id-type\":{\"S\":\"domain_q\"},\"range\":{\"N\":\"3\"}}"),
calls.getLast().body().path("RequestItems").path("metrics").get(0).path("DeleteRequest").path("Key"));
assertEquals(request.path("RequestItems"), reply.body().path("UnprocessedItems"));
assertEquals(2.0, reply.body().path("Responses").path("metrics").path("ConsumedCapacityUnits").asDouble());
calls.clear();
new DynamoDbLegacyProtocol(operations, SCOPE).execute("BatchWriteItem",
MAPPER.createObjectNode().set("RequestItems", reply.body().path("UnprocessedItems")));
assertEquals(2, calls.size());
}
@Test
void invalidLegacyKeysAndUnsupportedActionsNeverWrite() throws Exception {
List<Call> calls = new ArrayList<>();
DynamoDbOperations operations = call -> {
calls.add(call);
assertEquals("DescribeTable", call.action());
return reply(TABLE);
};
for (String request : List.of(
"{\"TableName\":\"metrics\"}",
"{\"TableName\":\"metrics\",\"HashKeyValue\":\"bad\"}",
"{\"TableName\":\"metrics\",\"HashKeyValue\":{\"S\":\"x\"},\"ExclusiveStartKey\":{\"HashKeyElement\":{\"S\":\"x\"}}}",
"{\"TableName\":\"metrics\",\"HashKeyValue\":{\"S\":\"x\"},\"Count\":\"true\"}")) {
assertThrows(AwsException.class, () -> new DynamoDbLegacyProtocol(operations, SCOPE)
.execute("Query", json(request)));
}
assertThrows(AwsException.class, () -> new DynamoDbLegacyProtocol(operations, SCOPE)
.execute("BatchWriteItem", json("""
{"RequestItems":{"metrics":[{"DeleteRequest":{"Key":{"HashKeyElement":{"S":"x"}}}}]}}
""")));
calls.clear();
assertThrows(AwsException.class, () -> new DynamoDbLegacyProtocol(operations, SCOPE)
.execute("CreateTable", json("{}")));
assertTrue(calls.isEmpty());
}
@Test
void missingOrDeniedMetadataCannotReachQueryOrWrite() throws Exception {
for (String action : List.of("Query", "BatchWriteItem")) {
List<Call> calls = new ArrayList<>();
DynamoDbOperations operations = call -> {
calls.add(call);
return new Reply(400, json("{\"__type\":\"AccessDeniedException\",\"message\":\"denied\"}"), Map.of());
};
assertThrows(AwsException.class, () -> new DynamoDbLegacyProtocol(operations, SCOPE).execute(action,
json("Query".equals(action)
? "{\"TableName\":\"metrics\",\"HashKeyValue\":{\"S\":\"x\"}}"
: "{\"RequestItems\":{\"metrics\":[{\"DeleteRequest\":{\"Key\":{}}}]}}")));
assertEquals(List.of("DescribeTable"), calls.stream().map(Call::action).toList());
}
}
private static JsonNode json(String value) throws Exception {
return MAPPER.readTree(value);
}
private static Reply reply(String value) throws Exception {
return new Reply(200, json(value), Map.of());
}
}
@@ -14,6 +14,7 @@ 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.assertSame;
class DynamoDbResponsesTest {
@@ -112,4 +113,28 @@ class DynamoDbResponsesTest {
void withCrc32_nullResponse_returnsNull() {
assertNull(DynamoDbResponses.withCrc32(null, mapper));
}
@Test
void legacyErrorsRetainMessageHeadersAndOriginalBackendBody() {
ObjectNode entity = mapper.createObjectNode()
.put("__type", "com.amazonaws.dynamodb.v20120810#ResourceNotFoundException")
.put("message", "Table not found");
Response input = Response.status(400).entity(entity).header("x-request-id", "probe").build();
Response legacy = DynamoDbResponses.withLegacyErrorNamespace(input, mapper);
ObjectNode body = (ObjectNode) legacy.getEntity();
assertEquals("com.amazonaws.dynamodb.v20111205#ResourceNotFoundException", body.path("__type").asText());
assertEquals("Table not found", body.path("message").asText());
assertEquals("probe", legacy.getHeaderString("x-request-id"));
assertEquals(400, legacy.getStatus());
assertEquals("com.amazonaws.dynamodb.v20120810#ResourceNotFoundException", entity.path("__type").asText());
}
@Test
void legacyResponsesPreserveCoralValidationAndSuccessfulBodies() {
Response validation = Response.status(400).entity(mapper.createObjectNode()
.put("__type", "com.amazon.coral.validate#ValidationException")).build();
assertSame(validation, DynamoDbResponses.withLegacyErrorNamespace(validation, mapper));
Response success = Response.ok(mapper.createObjectNode().put("Count", 1)).build();
assertSame(success, DynamoDbResponses.withLegacyErrorNamespace(success, mapper));
}
}
@@ -153,7 +153,7 @@ class DynamoDbFacadeTest {
requestContext.setRegion(OTHER_REGION);
IamConditionContextResolver resolver = new IamConditionContextResolver(dynamoDb,
mock(Instance.class), mock(Instance.class), mock(Instance.class), requestContext, mock(EmulatorConfig.class),
null);
null, mock(io.github.hectorvent.floci.core.common.ResolvedServiceCatalog.class));
ContainerRequestContext request = mock(ContainerRequestContext.class);
JsonNode body = mapper.readTree("""
{"TableName": "recorded-table", "Key": {"id": {"S": "USER_alice"}}}
@@ -36,6 +36,99 @@ class DynamoDbFgacEnforcementIntegrationTest {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@ParameterizedTest
@ValueSource(strings = {"Query", "BatchWriteItem"})
void legacyKeysCannotBypassLeadingKeyPolicyWithoutNullGuard(String action) {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String tableName = "fgac-legacy-" + suffix;
String roleName = "FgacLegacyRole" + suffix;
given().header("Authorization", auth(ROLE_ACCOUNT_ID, "dynamodb"))
.header("X-Amz-Target", "DynamoDB_20120810.CreateTable").contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{"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)).post("/").then().statusCode(200);
createRole(roleName);
putBroadDynamoDbRolePolicy(roleName);
String accessKey = assumeRoleWithLeadingKeysSessionPolicy(roleName, false);
for (String user : new String[]{"USER_bob", "USER_alice"}) {
String body = "Query".equals(action)
? """
{"TableName":"%s","HashKeyValue":{"S":"%s"}}
""".formatted(tableName, user)
: """
{"RequestItems":{"%s":[{"DeleteRequest":{"Key":{
"HashKeyElement":{"S":"%s"},"RangeKeyElement":{"S":"profile"}}}}]}}
""".formatted(tableName, user);
if ("USER_bob".equals(user)) {
given().header("Authorization", auth(accessKey, "dynamodb"))
.header("X-Amz-Target", "DynamoDB_20111205." + action)
.contentType(DYNAMODB_CONTENT_TYPE).body(body).post("/").then()
.statusCode(400).body(containsString("AccessDeniedException"));
} else {
given().header("Authorization", auth(accessKey, "dynamodb"))
.header("X-Amz-Target", "DynamoDB_20111205." + action)
.contentType(DYNAMODB_CONTENT_TYPE).body(body).post("/").then().statusCode(200);
}
}
}
@Test
void legacyQueryHonorsProjectedAttributesAndExplicitPartitionDeny() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String tableName = "fgac-legacy-attributes-" + suffix;
String roleName = "FgacLegacyAttributes" + suffix;
given().header("Authorization", auth(ROLE_ACCOUNT_ID, "dynamodb"))
.header("X-Amz-Target", "DynamoDB_20120810.CreateTable").contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{"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)).post("/").then().statusCode(200);
given().header("Authorization", auth(ROLE_ACCOUNT_ID, "dynamodb"))
.header("X-Amz-Target", "DynamoDB_20120810.PutItem").contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{"TableName":"%s","Item":{"PK":{"S":"USER_alice"},"SK":{"S":"one"},
"public":{"S":"visible"},"secret":{"S":"fixture-private"}}}
""".formatted(tableName)).post("/").then().statusCode(200);
createRole(roleName);
putBroadDynamoDbRolePolicy(roleName);
String accessKey = assumeRoleWithSessionPolicy(roleName, """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"dynamodb:Query","Resource":"*",
"Condition":{"ForAllValues:StringEquals":{"dynamodb:Attributes":["PK","SK","public"]}}},
{"Effect":"Deny","Action":"dynamodb:Query","Resource":"*",
"Condition":{"ForAnyValue:StringEquals":{"dynamodb:LeadingKeys":["USER_denied"]}}}]}
""");
for (String[] query : new String[][]{
{"USER_alice", "public", "200"}, {"USER_alice", "secret", "400"}, {"USER_denied", "public", "400"}}) {
if ("200".equals(query[2])) {
given().header("Authorization", auth(accessKey, "dynamodb"))
.header("X-Amz-Target", "DynamoDB_20111205.Query").contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{"TableName":"%s","HashKeyValue":{"S":"%s"},"AttributesToGet":["%s"]}
""".formatted(tableName, query[0], query[1]))
.post("/").then().statusCode(200);
} else {
given().header("Authorization", auth(accessKey, "dynamodb"))
.header("X-Amz-Target", "DynamoDB_20111205.Query").contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{"TableName":"%s","HashKeyValue":{"S":"%s"},"AttributesToGet":["%s"]}
""".formatted(tableName, query[0], query[1]))
.post("/").then().statusCode(400).body(containsString("AccessDeniedException"));
}
}
given().header("Authorization", auth(accessKey, "dynamodb"))
.header("X-Amz-Target", "DynamoDB_20111205.Query").contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{"TableName":"%s","HashKeyValue":{"S":"USER_alice"}}
""".formatted(tableName)).post("/").then().statusCode(200)
.body("Items[0].secret.S", equalTo("fixture-private"));
}
@Test
void leadingKeysScopedSessionReadsItsOwnPartitionAndIsDeniedAnotherTenants() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
@@ -393,6 +486,10 @@ class DynamoDbFgacEnforcementIntegrationTest {
"Condition":{"ForAllValues:StringLike":{"dynamodb:LeadingKeys":["USER_alice*"]}%s}}
]}
""".formatted(nullGuard ? ",\"Null\":{\"dynamodb:LeadingKeys\":\"false\"}" : "");
return assumeRoleWithSessionPolicy(roleName, policy);
}
private static String assumeRoleWithSessionPolicy(String roleName, String policy) {
return given()
.formParam("Action", "AssumeRole")
.formParam("RoleArn", "arn:aws:iam::" + ROLE_ACCOUNT_ID + ":role/" + roleName)