diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java index d191bb0139..6a048759b6 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java @@ -1,7 +1,10 @@ package io.github.hectorvent.floci.core.common; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectReader; import io.github.hectorvent.floci.services.acm.AcmJsonHandler; import io.github.hectorvent.floci.services.athena.AthenaJsonHandler; import io.github.hectorvent.floci.services.codebuild.CodeBuildJsonHandler; @@ -59,6 +62,7 @@ public class AwsJson11Controller { private static final Logger LOG = Logger.getLogger(AwsJson11Controller.class); private final ObjectMapper objectMapper; + private final ObjectReader strictBodyReader; private final ResolvedServiceCatalog catalog; private final RegionResolver regionResolver; private final SsmJsonHandler ssmJsonHandler; @@ -130,6 +134,7 @@ public class AwsJson11Controller { LightsailJsonHandler lightsailJsonHandler, CloudControlJsonHandler cloudControlJsonHandler) { this.objectMapper = objectMapper; + this.strictBodyReader = objectMapper.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); this.catalog = catalog; this.regionResolver = regionResolver; this.ssmJsonHandler = ssmJsonHandler; @@ -189,8 +194,14 @@ public class AwsJson11Controller { String action = targetMatch.action(); LOG.infov("AwsJson11Controller {0} action: {1}", serviceKey, action); + JsonNode request; + try { + request = strictBodyReader.readTree(body); + } catch (JsonProcessingException e) { + return JsonErrorResponseUtils.createSerializationErrorResponse(); + } + try { - JsonNode request = objectMapper.readTree(body); String region = regionResolver.resolveRegion(httpHeaders); Response delegated = switch (serviceKey) { diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonController.java index c78e9e8152..853a2d138a 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonController.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonController.java @@ -1,7 +1,10 @@ package io.github.hectorvent.floci.core.common; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectReader; import io.github.hectorvent.floci.services.cloudcontrol.CloudControlJsonHandler; import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsJsonHandler; import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler; @@ -32,6 +35,7 @@ public class AwsJsonController { private static final Logger LOG = Logger.getLogger(AwsJsonController.class); private final ObjectMapper objectMapper; + private final ObjectReader strictBodyReader; private final ResolvedServiceCatalog catalog; private final RegionResolver regionResolver; private final DynamoDbJsonHandler dynamoDbJsonHandler; @@ -52,6 +56,7 @@ public class AwsJsonController { CloudWatchMetricsJsonHandler cloudWatchMetricsJsonHandler, CloudControlJsonHandler cloudControlJsonHandler) { this.objectMapper = objectMapper; + this.strictBodyReader = objectMapper.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); this.catalog = catalog; this.regionResolver = regionResolver; this.dynamoDbJsonHandler = dynamoDbJsonHandler; @@ -84,9 +89,15 @@ public class AwsJsonController { String action = targetMatch.action(); LOG.debugv("{0} JSON action: {1}", serviceKey, action); + JsonNode request; + try { + request = strictBodyReader.readTree(body); + } catch (JsonProcessingException e) { + return JsonErrorResponseUtils.createSerializationErrorResponse(); + } + Response response; try { - JsonNode request = objectMapper.readTree(body); String region = regionResolver.resolveRegion(httpHeaders); response = switch (serviceKey) { diff --git a/src/main/java/io/github/hectorvent/floci/core/common/JsonErrorResponseUtils.java b/src/main/java/io/github/hectorvent/floci/core/common/JsonErrorResponseUtils.java index d51ba0fdc0..c9b084a585 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/JsonErrorResponseUtils.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/JsonErrorResponseUtils.java @@ -29,6 +29,18 @@ public class JsonErrorResponseUtils { "Unknown operation: " + target, null); } + /** + * A request body that is not valid JSON is a client (deserialization) error, not a server + * fault. AWS's JSON protocols reject it with 400 SerializationException; without this the + * unparsed body escapes to the generic catch and surfaces as 500 InternalFailure. + */ + public static Response createSerializationErrorResponse() { + return createErrorResponse(400, + "SerializationException", + "SerializationException", + "The request could not be parsed as valid JSON.", null); + } + public static Response createErrorResponse(int httpStatusCode, String queryError, String errorType, String errorMessage, JsonNode item) { String queryErrorFault = (httpStatusCode < 500) ? "Sender" : "Receiver"; if (item != null) { diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbStreamService.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbStreamService.java index d5b3e9f3c4..45794fa9fb 100644 --- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbStreamService.java +++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbStreamService.java @@ -255,7 +255,12 @@ public class DynamoDbStreamService { public GetRecordsResult getRecords(String shardIterator, Integer limit) { String[] parts = decodeIterator(shardIterator); String streamArn = parts[0]; - int position = Integer.parseInt(parts[1]); + int position; + try { + position = Integer.parseInt(parts[1]); + } catch (NumberFormatException e) { + throw new AwsException("ValidationException", "Invalid shard iterator", 400); + } ConcurrentLinkedDeque deque = records.get(streamArn); List snapshot = deque != null ? new ArrayList<>(deque) : List.of(); diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java index 757f0c9b4e..20c138ad97 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java +++ b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java @@ -18,7 +18,9 @@ import io.github.hectorvent.floci.services.eventbridge.model.Rule; import io.github.hectorvent.floci.services.eventbridge.model.RuleState; import io.github.hectorvent.floci.services.eventbridge.model.Target; import io.github.hectorvent.floci.services.resourcegroupstagging.ResourceGroupsTaggingService; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; @@ -531,6 +533,7 @@ public class EventBridgeService { try { if (policyJson != null && !policyJson.isBlank()) { + parseClientJson(policyJson, "Policy"); bus.setPolicy(policyJson); } else { String currentPolicy = bus.getPolicy(); @@ -558,7 +561,7 @@ public class EventBridgeService { statement.put("Action", action != null ? action : "events:PutEvents"); statement.put("Resource", bus.getArn()); if (conditionJson != null && !conditionJson.isBlank()) { - statement.set("Condition", objectMapper.readTree(conditionJson)); + statement.set("Condition", parseClientJson(conditionJson, "Condition")); } statements.add(statement); bus.setPolicy(objectMapper.writeValueAsString(policy)); @@ -573,6 +576,20 @@ public class EventBridgeService { LOG.infov("Put permission on bus {0}, statement {1}", effectiveBus, statementId); } + /** + * Parses client-supplied JSON (PutPermission Policy/Condition). Malformed input is a + * client error; without this it fell into the catch-all and surfaced as a 500. + */ + private JsonNode parseClientJson(String json, String field) { + try { + return objectMapper.reader() + .with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .readTree(json); + } catch (JsonProcessingException e) { + throw new AwsException("ValidationException", field + " is not valid JSON.", 400); + } + } + public void removePermission(String busName, String statementId, boolean removeAll, String region) { String effectiveBus = resolvedBusName(busName); if ("default".equals(effectiveBus)) { diff --git a/src/main/java/io/github/hectorvent/floci/services/kinesis/KinesisJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/kinesis/KinesisJsonHandler.java index f9e06e4a76..0634f84779 100644 --- a/src/main/java/io/github/hectorvent/floci/services/kinesis/KinesisJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/kinesis/KinesisJsonHandler.java @@ -408,7 +408,12 @@ public class KinesisJsonHandler { private Response handlePutRecord(JsonNode request, String region) { String streamName = resolveStreamName(request); - byte[] data = Base64.getDecoder().decode(request.path("Data").asText()); + byte[] data; + try { + data = Base64.getDecoder().decode(request.path("Data").asText()); + } catch (IllegalArgumentException e) { + throw new AwsException("SerializationException", "Data is not valid base64.", 400); + } String partitionKey = request.path("PartitionKey").asText(); KinesisService.PutRecordResult result = service.putRecordWithShardId(streamName, data, partitionKey, region); diff --git a/src/main/java/io/github/hectorvent/floci/services/kinesis/KinesisService.java b/src/main/java/io/github/hectorvent/floci/services/kinesis/KinesisService.java index 0cee292dbb..cea73014ff 100644 --- a/src/main/java/io/github/hectorvent/floci/services/kinesis/KinesisService.java +++ b/src/main/java/io/github/hectorvent/floci/services/kinesis/KinesisService.java @@ -390,17 +390,39 @@ public class KinesisService { return Base64.getEncoder().encodeToString(raw.getBytes(StandardCharsets.UTF_8)); } - public Map getRecords(String shardIterator, Integer limit, String region) { - byte[] decoded = Base64.getDecoder().decode(shardIterator); + // A shard iterator is an opaque token we mint; a client that replays a garbage one gets + // InvalidArgumentException, not a 500 from an unguarded base64 decode or Integer.parse. + private String[] decodeShardIterator(String shardIterator) { + byte[] decoded; + try { + decoded = Base64.getDecoder().decode(shardIterator); + } catch (IllegalArgumentException e) { + throw new AwsException("InvalidArgumentException", "Invalid shard iterator", 400); + } // Use limit=-1 so trailing empty slots round-trip and old 5-part iterators still work. String[] parts = new String(decoded, StandardCharsets.UTF_8).split(java.util.regex.Pattern.quote("|"), -1); - if (parts.length < 5) throw new AwsException("InvalidArgumentException", "Invalid shard iterator", 400); + if (parts.length < 5) { + throw new AwsException("InvalidArgumentException", "Invalid shard iterator", 400); + } + return parts; + } + + private int parseIteratorIndex(String value) { + try { + return Integer.parseInt(value); + } catch (NumberFormatException e) { + throw new AwsException("InvalidArgumentException", "Invalid shard iterator", 400); + } + } + + public Map getRecords(String shardIterator, Integer limit, String region) { + String[] parts = decodeShardIterator(shardIterator); String streamName = parts[0]; String shardId = parts[1]; String type = parts[2]; String startSeq = parts[3]; - int lastIndex = Integer.parseInt(parts[4]); + int lastIndex = parseIteratorIndex(parts[4]); Long timestampMillis = null; if (parts.length >= 6 && !parts[5].isEmpty()) { try { @@ -518,16 +540,12 @@ public class KinesisService { public Map getRecordsForAccount(String accountId, String shardIterator, Integer limit, String region) { - byte[] decoded = Base64.getDecoder().decode(shardIterator); - String[] parts = new String(decoded, StandardCharsets.UTF_8).split(java.util.regex.Pattern.quote("|"), -1); - if (parts.length < 5) { - throw new AwsException("InvalidArgumentException", "Invalid shard iterator", 400); - } + String[] parts = decodeShardIterator(shardIterator); String streamName = parts[0]; String shardId = parts[1]; String type = parts[2]; String startSeq = parts[3]; - int lastIndex = Integer.parseInt(parts[4]); + int lastIndex = parseIteratorIndex(parts[4]); KinesisStream stream = resolveStreamForAccount(accountId, streamName, region); KinesisShard shard = stream.getShards().stream() diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/KmsJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/kms/KmsJsonHandler.java index 1d864f8368..ca87355e0d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/kms/KmsJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/kms/KmsJsonHandler.java @@ -234,9 +234,20 @@ public class KmsJsonHandler { return Response.ok(objectMapper.createObjectNode()).build(); } + // Blob fields arrive base64-encoded on the wire. A value that is not valid base64 is a + // client deserialization error, not a server fault — without this the IllegalArgumentException + // escapes to the dispatcher's generic catch and surfaces as 500 InternalFailure. + private static byte[] decodeBlob(JsonNode request, String field) { + try { + return Base64.getDecoder().decode(request.path(field).asText()); + } catch (IllegalArgumentException e) { + throw new AwsException("SerializationException", field + " is not valid base64.", 400); + } + } + private Response handleEncrypt(JsonNode request, String region) { String keyId = request.path("KeyId").asText(); - byte[] plaintext = Base64.getDecoder().decode(request.path("Plaintext").asText()); + byte[] plaintext = decodeBlob(request, "Plaintext"); Map context = readEncryptionContext(request.path("EncryptionContext")); byte[] ciphertext = service.encrypt(keyId, plaintext, context, region); @@ -247,7 +258,7 @@ public class KmsJsonHandler { } private Response handleDecrypt(JsonNode request, String region) { - byte[] ciphertext = Base64.getDecoder().decode(request.path("CiphertextBlob").asText()); + byte[] ciphertext = decodeBlob(request, "CiphertextBlob"); Map context = readEncryptionContext(request.path("EncryptionContext")); KmsService.DecryptResult result = service.decryptAndResolveKey(ciphertext, context, region); @@ -289,7 +300,7 @@ public class KmsJsonHandler { } private Response handleReEncrypt(JsonNode request, String region) { - byte[] ciphertext = Base64.getDecoder().decode(request.path("CiphertextBlob").asText()); + byte[] ciphertext = decodeBlob(request, "CiphertextBlob"); String destKeyId = request.path("DestinationKeyId").asText(); Map sourceContext = readEncryptionContext(request.path("SourceEncryptionContext")); Map destContext = readEncryptionContext(request.path("DestinationEncryptionContext")); @@ -315,7 +326,7 @@ public class KmsJsonHandler { private Response handleSign(JsonNode request, String region) { String keyId = request.path("KeyId").asText(); - byte[] message = Base64.getDecoder().decode(request.path("Message").asText()); + byte[] message = decodeBlob(request, "Message"); String algorithm = request.path("SigningAlgorithm").asText("RSASSA_PSS_SHA_256"); KmsMessageType messageType = KmsMessageType.fromString(request.path("MessageType").asText("RAW")); @@ -330,8 +341,8 @@ public class KmsJsonHandler { private Response handleVerify(JsonNode request, String region) { String keyId = request.path("KeyId").asText(); - byte[] message = Base64.getDecoder().decode(request.path("Message").asText()); - byte[] signature = Base64.getDecoder().decode(request.path("Signature").asText()); + byte[] message = decodeBlob(request, "Message"); + byte[] signature = decodeBlob(request, "Signature"); String algorithm = request.path("SigningAlgorithm").asText("RSASSA_PSS_SHA_256"); KmsMessageType messageType = KmsMessageType.fromString(request.path("MessageType").asText("RAW")); @@ -346,7 +357,7 @@ public class KmsJsonHandler { private Response handleGenerateMac(JsonNode request, String region) { String keyId = request.path("KeyId").asText(); - byte[] message = Base64.getDecoder().decode(request.path("Message").asText()); + byte[] message = decodeBlob(request, "Message"); String algorithm = request.path("MacAlgorithm").asText(); KmsService.GenerateMacResult result = service.generateMacAndResolveKey(keyId, message, algorithm, region); @@ -360,8 +371,8 @@ public class KmsJsonHandler { private Response handleVerifyMac(JsonNode request, String region) { String keyId = request.path("KeyId").asText(); - byte[] message = Base64.getDecoder().decode(request.path("Message").asText()); - byte[] mac = Base64.getDecoder().decode(request.path("Mac").asText()); + byte[] message = decodeBlob(request, "Message"); + byte[] mac = decodeBlob(request, "Mac"); String algorithm = request.path("MacAlgorithm").asText(); KmsService.VerifyMacResult result = service.verifyMacAndResolveKey(keyId, message, mac, algorithm, region); diff --git a/src/test/java/io/github/hectorvent/floci/core/common/JsonMalformedInputIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/JsonMalformedInputIntegrationTest.java new file mode 100644 index 0000000000..a49ec3216d --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/JsonMalformedInputIntegrationTest.java @@ -0,0 +1,167 @@ +package io.github.hectorvent.floci.core.common; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.RestAssured; +import io.restassured.config.EncoderConfig; +import io.restassured.http.ContentType; +import io.restassured.parsing.Parser; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.startsWith; + +/** + * Malformed client input on a JSON-protocol service must yield a 4xx typed error, never a 500 + * InternalFailure. Both JSON dispatchers already render {@code AwsException} correctly; the leaks + * are (a) an unparseable request body reaching {@code objectMapper.readTree} and (b) service + * handlers that decode base64 / parse ints from client input without catching the failure. Each + * of those escapes the dispatcher's generic {@code catch (Exception)} and surfaces as 500. + * + *

Every case here asserts the status is a 4xx (never 500) and, where AWS defines it, the exact + * error code. Inputs are crafted to fail on the malformed value before any resource lookup, so no + * seeding is required. + */ +@QuarkusTest +class JsonMalformedInputIntegrationTest { + + private static final String JSON_1_1 = "application/x-amz-json-1.1"; + private static final String JSON_1_0 = "application/x-amz-json-1.0"; + + @BeforeAll + static void registerJsonParsers() { + RestAssured.registerParser(JSON_1_1, Parser.JSON); + RestAssured.registerParser(JSON_1_0, Parser.JSON); + } + + private static io.restassured.specification.RequestSpecification req(String contentType, String target, String body) { + // RestAssured has no built-in serializer for the x-amz-json content types; send the raw body as text. + return given() + .config(RestAssured.config().encoderConfig(EncoderConfig.encoderConfig() + .encodeContentTypeAs(JSON_1_1, ContentType.TEXT) + .encodeContentTypeAs(JSON_1_0, ContentType.TEXT))) + .header("X-Amz-Target", target) + .contentType(contentType) + .header("Authorization", + "AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/service/aws4_request") + .body(body); + } + + // ── Dispatcher: an unparseable body is a client deserialization error (both controllers) ── + + @Test + void malformedJsonBodyOnJson11IsSerializationException() { + req(JSON_1_1, "TrentService.CreateKey", "{ this is not json") + .when().post("/") + .then() + .statusCode(400) + .body("__type", equalTo("SerializationException")); + } + + @Test + void malformedJsonBodyOnJson10IsSerializationException() { + req(JSON_1_0, "DynamoDB_20120810.ListTables", "{ not json ]") + .when().post("/") + .then() + .statusCode(400) + .body("__type", equalTo("SerializationException")); + } + + @Test + void trailingContentAfterValidJsonOnJson11IsSerializationException() { + // Jackson's default readTree stops at the first complete value; without + // FAIL_ON_TRAILING_TOKENS the garbage after {} is silently ignored. + req(JSON_1_1, "TrentService.CreateKey", "{} not-json") + .when().post("/") + .then() + .statusCode(400) + .body("__type", equalTo("SerializationException")); + } + + @Test + void trailingContentAfterValidJsonOnJson10IsSerializationException() { + req(JSON_1_0, "DynamoDB_20120810.ListTables", "{}{\"second\":\"document\"}") + .when().post("/") + .then() + .statusCode(400) + .body("__type", equalTo("SerializationException")); + } + + @Test + void trailingWhitespaceAfterValidJsonIsAccepted() { + req(JSON_1_0, "DynamoDB_20120810.ListTables", "{} \n") + .when().post("/") + .then() + .statusCode(200); + } + + // ── KMS: base64 blob fields ── + + @Test + void kmsDecryptMalformedCiphertextIsNot500() { + req(JSON_1_1, "TrentService.Decrypt", "{\"CiphertextBlob\":\"!!!not-base64!!!\"}") + .when().post("/") + .then() + .statusCode(400) + .body("__type", equalTo("SerializationException")); + } + + @Test + void kmsEncryptMalformedPlaintextIsNot500() { + req(JSON_1_1, "TrentService.Encrypt", "{\"KeyId\":\"k\",\"Plaintext\":\"@@notbase64@@\"}") + .when().post("/") + .then() + .statusCode(400) + .body("__type", equalTo("SerializationException")); + } + + // ── Kinesis: shard iterator (opaque token we mint) and the PutRecord data blob ── + + @Test + void kinesisGetRecordsMalformedShardIteratorIsInvalidArgument() { + req(JSON_1_1, "Kinesis_20131202.GetRecords", "{\"ShardIterator\":\"!!!not-base64!!!\"}") + .when().post("/") + .then() + .statusCode(400) + .body("__type", startsWith("InvalidArgumentException")); + } + + @Test + void kinesisGetRecordsIteratorWithNonNumericIndexIsInvalidArgument() { + // valid base64 of "stream|shard|type|seq|NOTANUMBER" — decodes fine, parseInt(index) would throw + String iterator = java.util.Base64.getEncoder() + .encodeToString("s|shard-0|AT|0|xyz".getBytes(java.nio.charset.StandardCharsets.UTF_8)); + req(JSON_1_1, "Kinesis_20131202.GetRecords", "{\"ShardIterator\":\"" + iterator + "\"}") + .when().post("/") + .then() + .statusCode(400) + .body("__type", startsWith("InvalidArgumentException")); + } + + @Test + void kinesisPutRecordMalformedDataIsSerializationException() { + req(JSON_1_1, "Kinesis_20131202.PutRecord", + "{\"StreamName\":\"s\",\"PartitionKey\":\"p\",\"Data\":\"@@notbase64@@\"}") + .when().post("/") + .then() + .statusCode(400) + .body("__type", equalTo("SerializationException")); + } + + // ── DynamoDB Streams: iterator base64 is guarded, the position parseInt was not ── + + @Test + void dynamoDbStreamsGetRecordsIteratorWithNonNumericPositionIsNot500() { + // valid base64 of "arn|NOTANUMBER" — decodeIterator succeeds, Integer.parseInt(position) would throw + String iterator = java.util.Base64.getEncoder() + .encodeToString("arn:aws:dynamodb:us-east-1:0:table/T/stream/x|notanumber" + .getBytes(java.nio.charset.StandardCharsets.UTF_8)); + req(JSON_1_0, "DynamoDBStreams_20120810.GetRecords", "{\"ShardIterator\":\"" + iterator + "\"}") + .when().post("/") + .then() + .statusCode(400) + .body("__type", not(equalTo("InternalFailure"))); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgePermissionIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgePermissionIntegrationTest.java index 381df5c5a7..008558f1fa 100644 --- a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgePermissionIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgePermissionIntegrationTest.java @@ -230,4 +230,63 @@ class EventBridgePermissionIntegrationTest { .statusCode(200) .body("Policy", containsString("default-stmt")); } + + @Test + @Order(8) + void putPermissionWithMalformedPolicyIsValidationException() { + // Regression: a malformed Policy was stored unvalidated, and every later + // permission call parsing it fell into the catch-all and surfaced as 500. + given() + .contentType(EVENT_BRIDGE_CONTENT_TYPE) + .header("X-Amz-Target", "AWSEvents.PutPermission") + .body(""" + { + "EventBusName": "perm-test-bus", + "Policy": "{\\"Version\\": not-valid" + } + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")); + + // The malformed policy must not have been stored: subsequent permission + // operations on the bus keep working instead of failing on parse. + given() + .contentType(EVENT_BRIDGE_CONTENT_TYPE) + .header("X-Amz-Target", "AWSEvents.PutPermission") + .body(""" + { + "EventBusName": "perm-test-bus", + "Action": "events:PutEvents", + "Principal": "*", + "StatementId": "after-bad-policy" + } + """) + .when() + .post("/") + .then() + .statusCode(200); + } + + @Test + void putPermissionPolicyWithTrailingContentIsValidationException() { + // A lenient readTree accepts '{} garbage' by stopping at the first value; + // the policy must be parsed with trailing-token validation enabled. + given() + .contentType(EVENT_BRIDGE_CONTENT_TYPE) + .header("X-Amz-Target", "AWSEvents.PutPermission") + .body(""" + { + "EventBusName": "perm-test-bus", + "Policy": "{} trailing-garbage" + } + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")); + } }