mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
fix: return 4xx client errors instead of 500 for malformed JSON-protocol input (#1926)
* fix: return 4xx client errors instead of 500 for malformed JSON-protocol input
Parse request bodies up front in both JSON dispatchers and return 400
SerializationException for unparseable payloads. Convert input-parsing
failures that previously fell into the catch-all 500 InternalFailure into
their modeled client errors: KMS base64 blob decodes (SerializationException),
Kinesis shard iterators and record data (InvalidArgumentException/
SerializationException), DynamoDB Streams iterator positions
(ValidationException), and EventBridge PutPermission Policy/Condition JSON
(ValidationException; a malformed Policy was previously stored raw and
silently accepted).
* fix: reject trailing content after a valid JSON request body
Jackson's default readTree stops at the first complete JSON value, so a
body like '{} garbage' bypassed the new up-front SerializationException
check and was processed as if the trailing content weren't there. Parse
dispatcher bodies and EventBridge PutPermission Policy/Condition with
FAIL_ON_TRAILING_TOKENS; trailing whitespace remains accepted.
This commit is contained in:
1 parent
1c8b851bea
commit
b0e56a9a45
10 files changed
+340
-24
No files matched your search
@@ -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) {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
+6
-1
@@ -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<DynamoDbStreamRecord> deque = records.get(streamArn);
|
||||
List<DynamoDbStreamRecord> snapshot = deque != null ? new ArrayList<>(deque) : List.of();
|
||||
|
||||
+18
-1
@@ -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)) {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -390,17 +390,39 @@ public class KinesisService {
|
||||
return Base64.getEncoder().encodeToString(raw.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
public Map<String, Object> 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<String, Object> 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<String, Object> 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()
|
||||
|
||||
@@ -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<String, String> 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<String, String> 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<String, String> sourceContext = readEncryptionContext(request.path("SourceEncryptionContext"));
|
||||
Map<String, String> 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);
|
||||
|
||||
Reference in new issue
Block a user