fix(ssm): parse and bound command delivery timeouts (#5908)

* fix(ssm): limit public command delivery time

* docs(ssm): describe command delivery timeouts

* fix(ssm): deserialize delivery timeouts before checking bounds

Handle numeric delivery timeouts consistently without bypassing limits.

* fix(ssm): report member-specific deserialization errors

Name the expected scalar type and explain malformed structures.

* refactor(ssm): keep delivery timeout errors consistent
This commit is contained in:
David Phillips authored and GitHub committed 2026-10-18 11:03:48 -04:00
1 parent 1a80884f40
commit 356c79e78e
9 files changed
+536 -14

No files matched your search

@@ -0,0 +1,83 @@
package com.floci.test;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import software.amazon.awssdk.services.ssm.SsmClient;
import software.amazon.awssdk.services.ssm.model.Command;
import software.amazon.awssdk.services.ssm.model.SendCommandRequest;
import software.amazon.awssdk.services.ssm.model.SsmException;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
@DisplayName("SSM public delivery limits")
class SsmDeliveryLimitTest {
@ParameterizedTest
@ValueSource(ints = {2592001, Integer.MAX_VALUE})
void rejectsOversizedDeliveryWithoutCreatingWork(int timeout) {
assumeFalse(TestFixtures.isRealAws(), "Uses an emulator-only managed node");
String instance = "i-" + UUID.randomUUID().toString().replace("-", "").substring(0, 17);
try (SsmClient client = TestFixtures.ssmClient()) {
try {
SsmException error = assertThrows(SsmException.class,
() -> client.sendCommand(request(instance).timeoutSeconds(timeout).build()));
assertEquals(400, error.statusCode());
assertEquals("ValidationException", error.awsErrorDetails().errorCode());
assertTrue(client.listCommands(r -> r.instanceId(instance)).commands().isEmpty());
Command retry = client.sendCommand(request(instance).timeoutSeconds(30).build()).command();
assertEquals(30, retry.timeoutSeconds());
assertEquals(1, client.listCommands(r -> r.instanceId(instance)).commands().size());
} finally {
cancelOwned(client, instance);
}
}
}
@ParameterizedTest
@ValueSource(ints = {30, 2592000})
void acceptsInclusiveDeliveryBounds(int timeout) {
assumeFalse(TestFixtures.isRealAws(), "Uses an emulator-only managed node");
String instance = "i-" + UUID.randomUUID().toString().replace("-", "").substring(0, 17);
try (SsmClient client = TestFixtures.ssmClient()) {
try {
Command command = client.sendCommand(request(instance).timeoutSeconds(timeout).build()).command();
assertEquals(timeout, command.timeoutSeconds());
assertEquals(command.commandId(), client.listCommands(r -> r.instanceId(instance))
.commands().get(0).commandId());
} finally {
cancelOwned(client, instance);
}
}
}
@Test
void preservesOmittedDeliveryDefault() {
assumeFalse(TestFixtures.isRealAws(), "Uses an emulator-only managed node");
String instance = "i-" + UUID.randomUUID().toString().replace("-", "").substring(0, 17);
try (SsmClient client = TestFixtures.ssmClient()) {
try {
assertEquals(3600, client.sendCommand(request(instance).build()).command().timeoutSeconds());
} finally {
cancelOwned(client, instance);
}
}
}
private static SendCommandRequest.Builder request(String instance) {
return SendCommandRequest.builder().documentName("AWS-RunShellScript").instanceIds(instance)
.parameters(Map.of("commands", List.of("echo limit")));
}
private static void cancelOwned(SsmClient client, String instance) {
assertAll(client.listCommands(r -> r.instanceId(instance)).commands().stream()
.map(command -> (Executable) () ->
client.cancelCommand(r -> r.commandId(command.commandId()))));
}
}
+6
View File
@@ -49,6 +49,12 @@
`SendCommand` supports the `AWS-RunShellScript` document. For EC2 instances launched by Floci in real Docker mode, Floci creates the command invocation, returns the command response, and then runs the script asynchronously inside the target instance container. Callers observe completion through `GetCommandInvocation`. `stdout`, `stderr`, response code, start time, and end time are recorded on the invocation.
For public `SendCommand`, set `TimeoutSeconds` to a delivery/start allowance from 30 to
2,592,000 seconds. The default is 3,600 seconds. Floci does not automatically expire
commands waiting for an agent, so a command that is never delivered can remain pending
indefinitely. The document's execution allowance and internal CodeDeploy hook budgets
are separate.
If the target is not a Floci EC2 container, or if the document is not supported for direct execution, Floci falls back to the SSM agent polling flow. In that mode, `SendCommand` queues an ec2messages payload and the invocation completes after an agent calls `SendReply`.
Background execution retains the issuing account and region. Agent queues and message correlations
@@ -48,6 +48,7 @@ public class SsmCommandService implements Resettable {
private static final Logger LOG = Logger.getLogger(SsmCommandService.class);
private static final int MIN_TIMEOUT_SECONDS = 30;
private static final int MAX_TIMEOUT_SECONDS = 2_592_000;
private static final int MAX_INSTANCE_IDS = 50;
private static final int DEFAULT_SHELL_EXECUTION_TIMEOUT_SECONDS = 3600;
private static final int MAX_SHELL_EXECUTION_TIMEOUT_SECONDS = 172800;
@@ -165,7 +166,7 @@ public class SsmCommandService implements Resettable {
Map<String, List<String>> parameters = publicShell
? parseShellParameters(request.path("Parameters")) : parseParameters(request.path("Parameters"));
String comment = request.path("Comment").asText("");
int timeoutSeconds = request.path("TimeoutSeconds").asInt(3600);
int timeoutSeconds = SsmJsonDeserialization.optionalInteger(request.path("TimeoutSeconds"), 3600);
validateTimeoutSeconds(timeoutSeconds);
int executionTimeoutSeconds = publicShell ? shellExecutionTimeout(parameters) : timeoutSeconds;
int documentTimeoutDefault = publicShell ? DEFAULT_SHELL_EXECUTION_TIMEOUT_SECONDS : timeoutSeconds;
@@ -296,6 +297,10 @@ public class SsmCommandService implements Resettable {
throw SmithyValidationErrors.validationException(
"Value '" + timeoutSeconds + "' at 'timeoutSeconds' failed to satisfy constraint: Member must have value greater than or equal to 30");
}
if (timeoutSeconds > MAX_TIMEOUT_SECONDS) {
throw SmithyValidationErrors.validationException(
"Value '" + timeoutSeconds + "' at 'timeoutSeconds' failed to satisfy constraint: Member must have value less than or equal to 2592000");
}
}
public CommandInvocation getCommandInvocation(String commandId, String instanceId, String region) {
@@ -0,0 +1,41 @@
package io.github.hectorvent.floci.services.ssm;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.core.common.AwsException;
final class SsmJsonDeserialization {
private SsmJsonDeserialization() {
}
static int optionalInteger(JsonNode node, int defaultValue) {
if (node.isMissingNode() || node.isNull()) {
return defaultValue;
}
if (!node.isNumber() || Double.isNaN(node.doubleValue())) {
throw serializationException(node, "an Integer");
}
double value = node.doubleValue();
if (value >= Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
if (value <= Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
return node.intValue();
}
static AwsException serializationException(JsonNode node, String targetDescription) {
String token = switch (node.getNodeType()) {
case STRING -> "STRING_VALUE";
case NUMBER -> "NUMBER_VALUE";
case BOOLEAN -> node.booleanValue() ? "TRUE_VALUE" : "FALSE_VALUE";
default -> node.getNodeType().name();
};
String message = switch (node.getNodeType()) {
case OBJECT -> "Start of structure or map found where not expected.";
case ARRAY -> "Start of list found where not expected";
default -> token + " can not be converted to " + targetDescription;
};
return new AwsException("SerializationException", message, 400);
}
}
@@ -38,6 +38,8 @@ import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import static io.github.hectorvent.floci.services.ssm.SsmJsonDeserialization.serializationException;
@ApplicationScoped
public class SsmJsonHandler {
@@ -1039,7 +1041,7 @@ public class SsmJsonHandler {
} else if (l.isTextual()) {
labels.add(l.textValue());
} else {
throw serializationException(l, "String");
throw serializationException(l, "a String");
}
}
return labels;
@@ -1051,7 +1053,7 @@ public class SsmJsonHandler {
return null;
}
if (!node.isTextual()) {
throw serializationException(node, "String");
throw serializationException(node, "a String");
}
return node.textValue();
}
@@ -1063,21 +1065,11 @@ public class SsmJsonHandler {
return null;
}
if (!node.isNumber()) {
throw serializationException(node, "Long");
throw serializationException(node, "a Long");
}
return node.decimalValue().max(LONG_MIN).min(LONG_MAX).longValue();
}
private static AwsException serializationException(JsonNode node, String targetType) {
String token = switch (node.getNodeType()) {
case STRING -> "STRING_VALUE";
case NUMBER -> "NUMBER_VALUE";
case BOOLEAN -> node.booleanValue() ? "TRUE_VALUE" : "FALSE_VALUE";
default -> node.getNodeType().name();
};
return new AwsException("SerializationException", token + " can not be converted to a " + targetType, 400);
}
private Response handleLabelParameterVersion(JsonNode request, String region) {
String name = request.path("Name").asText();
Long parameterVersion = request.hasNonNull("ParameterVersion")
@@ -0,0 +1,196 @@
package io.github.hectorvent.floci.services.ssm;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
@QuarkusTest
class SsmDeliveryIntegerIntegrationTest extends SsmCommandIntegrationFixture {
private static final String ACCOUNT = "222222222222";
private static final String REGION = "us-west-2";
@Inject ObjectMapper mapper;
static Stream<Arguments> nonNumericTimeouts() {
return Stream.of(
Arguments.of("\"30\"", "STRING_VALUE can not be converted to an Integer"),
Arguments.of("\"bad\"", "STRING_VALUE can not be converted to an Integer"),
Arguments.of("{}", "Start of structure or map found where not expected."),
Arguments.of("true", "TRUE_VALUE can not be converted to an Integer"),
Arguments.of("false", "FALSE_VALUE can not be converted to an Integer"),
Arguments.of("[]", "Start of list found where not expected"));
}
@ParameterizedTest
@MethodSource("nonNumericTimeouts")
void nonNumericTimeoutIsRejectedBeforeAllocation(String input, String expectedMessage) throws Exception {
String instance = "i-integer-" + UUID.randomUUID();
try {
ObjectNode request = request(instance);
Response rejected = sendWithTimeout(request, input);
assertAll("serialization rejection leaves owned work unchanged",
() -> assertEquals(400, rejected.statusCode()),
() -> assertEquals("SerializationException", rejected.jsonPath().getString("__type")),
() -> assertEquals(expectedMessage,
rejected.jsonPath().getString("message")),
() -> assertTrue(RequestScopes.callAs(ACCOUNT, REGION,
() -> commandService.listCommands(null, instance, REGION)).isEmpty()),
() -> verifyNoInteractions(executor));
request.put("TimeoutSeconds", 30);
Response retry = send(request);
assertEquals(200, retry.statusCode());
assertEquals(30, retry.jsonPath().getInt("Command.TimeoutSeconds"));
assertEquals(1, RequestScopes.callAs(ACCOUNT, REGION,
() -> commandService.listCommands(null, instance, REGION)).size());
} finally {
cleanupCommands(ACCOUNT, REGION, instance);
}
}
@ParameterizedTest
@ValueSource(strings = {"30.0", "30.5", "30.9", "3e1"})
void numericTimeoutsAreTruncatedToTheDeliveryAllowance(String input) throws Exception {
String instance = "i-integer-" + UUID.randomUUID();
try {
ObjectNode request = request(instance);
Response response = sendWithTimeout(request, input);
assertEquals(200, response.statusCode());
assertEquals(30, response.jsonPath().getInt("Command.TimeoutSeconds"));
assertEquals(30, RequestScopes.callAs(ACCOUNT, REGION,
() -> commandService.listCommands(null, instance, REGION)).getFirst().getTimeoutSeconds());
verify(executor).supports(ACCOUNT, instance, "AWS-RunShellScript");
verifyNoMoreInteractions(executor);
} finally {
cleanupCommands(ACCOUNT, REGION, instance);
}
}
@ParameterizedTest
@ValueSource(strings = {"4294967356", "8589934652", "2592001.5", "1e400"})
void normalizedOverflowIsRejectedByDeliveryMaximum(String input) throws Exception {
String instance = "i-combined-" + UUID.randomUUID();
try {
ObjectNode request = request(instance);
Response rejected = sendWithTimeout(request, input);
assertAll("numeric normalization cannot bypass the delivery maximum",
() -> assertEquals(400, rejected.statusCode()),
() -> assertEquals("ValidationException", rejected.jsonPath().getString("__type")),
() -> assertTrue(String.valueOf(rejected.jsonPath().getString("message"))
.contains("less than or equal to 2592000")),
() -> assertTrue(RequestScopes.callAs(ACCOUNT, REGION,
() -> commandService.listCommands(null, instance, REGION)).isEmpty()),
() -> verifyNoInteractions(executor));
request.put("TimeoutSeconds", 30);
assertEquals(200, send(request).statusCode());
} finally {
cleanupCommands(ACCOUNT, REGION, instance);
}
}
@ParameterizedTest
@ValueSource(strings = {"2592000.9", "2.5920009e6"})
void truncationAtTheInclusiveMaximumRemainsAccepted(String input) throws Exception {
String instance = "i-combined-" + UUID.randomUUID();
try {
Response response = sendWithTimeout(request(instance), input);
assertEquals(200, response.statusCode());
assertEquals(2592000, response.jsonPath().getInt("Command.TimeoutSeconds"));
assertEquals(2592000, RequestScopes.callAs(ACCOUNT, REGION,
() -> commandService.listCommands(null, instance, REGION)).getFirst().getTimeoutSeconds());
verify(executor).supports(ACCOUNT, instance, "AWS-RunShellScript");
verifyNoMoreInteractions(executor);
} finally {
cleanupCommands(ACCOUNT, REGION, instance);
}
}
@ParameterizedTest
@ValueSource(strings = {"29.9", "-2147483649", "-1e400"})
void normalizedValuesStillPassThroughTheDeliveryMinimum(String input) throws Exception {
String instance = "i-integer-" + UUID.randomUUID();
try {
ObjectNode request = request(instance);
Response rejected = sendWithTimeout(request, input);
assertAll(
() -> assertEquals(400, rejected.statusCode()),
() -> assertEquals("ValidationException", rejected.jsonPath().getString("__type")),
() -> assertTrue(rejected.jsonPath().getString("message")
.contains("greater than or equal to 30")),
() -> assertTrue(RequestScopes.callAs(ACCOUNT, REGION,
() -> commandService.listCommands(null, instance, REGION)).isEmpty()),
() -> verifyNoInteractions(executor));
request.put("TimeoutSeconds", 30);
assertEquals(200, send(request).statusCode());
} finally {
cleanupCommands(ACCOUNT, REGION, instance);
}
}
@ParameterizedTest
@ValueSource(strings = {"30", "2592000", "missing", "null"})
void integersAndExistingDefaultsRemainUnchanged(String input) throws Exception {
String instance = "i-integer-" + UUID.randomUUID();
try {
ObjectNode request = request(instance);
if (!"missing".equals(input)) {
request.set("TimeoutSeconds", mapper.readTree(input));
}
Response response = send(request);
assertEquals(200, response.statusCode());
int expected = "missing".equals(input) || "null".equals(input) ? 3600 : Integer.parseInt(input);
assertEquals(expected, response.jsonPath().getInt("Command.TimeoutSeconds"));
} finally {
cleanupCommands(ACCOUNT, REGION, instance);
}
}
@Test
void internalHookKeepsItsOneSecondBudget() {
String instance = "i-integer-" + UUID.randomUUID();
try {
RequestScopes.runAs(ACCOUNT, REGION, () -> commandService.sendCommandToInstance(instance,
"AWS-RunShellScript", Map.of("commands", List.of("echo hook")), 1, REGION));
assertEquals(1, RequestScopes.callAs(ACCOUNT, REGION,
() -> commandService.listCommands(null, instance, REGION)).getFirst().getTimeoutSeconds());
verifyNoInteractions(executor);
} finally {
cleanupCommands(ACCOUNT, REGION, instance);
}
}
private ObjectNode request(String instance) {
ObjectNode request = mapper.createObjectNode();
request.put("DocumentName", "AWS-RunShellScript");
request.putArray("InstanceIds").add(instance);
request.putObject("Parameters").putArray("commands").add("echo integer");
return request;
}
private Response sendWithTimeout(ObjectNode request, String timeout) {
String body = request.toString();
return call(ACCOUNT, REGION, "AmazonSSM.SendCommand",
body.substring(0, body.length() - 1) + ",\"TimeoutSeconds\":" + timeout + "}");
}
private Response send(JsonNode request) {
return call(ACCOUNT, REGION, "AmazonSSM.SendCommand", request.toString());
}
}
@@ -0,0 +1,114 @@
package io.github.hectorvent.floci.services.ssm;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.services.ssm.model.Command;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.verifyNoInteractions;
@QuarkusTest
class SsmDeliveryLimitIntegrationTest extends SsmCommandIntegrationFixture {
private static final String ACCOUNT = "222222222222";
private static final String REGION = "us-west-2";
@ParameterizedTest
@CsvSource({"AWS-RunShellScript,2592001", "AWS-RunShellScript,2147483647",
"CustomDocument,2592001", "CustomDocument,2147483647"})
void oversizedDeliveryIsRejectedBeforeAllocation(String document, int timeout) {
String instance = "i-limit-" + UUID.randomUUID();
try {
Response rejected = send(document, instance, timeout);
assertEquals(400, rejected.statusCode());
assertEquals("ValidationException", rejected.jsonPath().getString("__type"));
assertEquals("1 validation error detected: Value '" + timeout
+ "' at 'timeoutSeconds' failed to satisfy constraint: "
+ "Member must have value less than or equal to 2592000",
rejected.jsonPath().getString("message"));
assertTrue(ownedCommands(instance).isEmpty());
verifyNoInteractions(executor);
Response retry = send(document, instance, 30);
assertEquals(200, retry.statusCode());
assertEquals(30, retry.jsonPath().getInt("Command.TimeoutSeconds"));
assertEquals(1, ownedCommands(instance).size());
} finally {
cleanup(instance);
}
}
@ParameterizedTest
@CsvSource({"AWS-RunShellScript,30", "AWS-RunShellScript,2592000",
"CustomDocument,30", "CustomDocument,2592000"})
void inclusiveDeliveryBoundsRemainAccepted(String document, int timeout) {
String instance = "i-limit-" + UUID.randomUUID();
try {
Response response = send(document, instance, timeout);
assertEquals(200, response.statusCode());
assertEquals(timeout, response.jsonPath().getInt("Command.TimeoutSeconds"));
assertEquals(1, ownedCommands(instance).size());
} finally {
cleanup(instance);
}
}
@ParameterizedTest
@CsvSource({"AWS-RunShellScript", "CustomDocument"})
void omissionAndExistingMinimumRemainUnchanged(String document) {
String instance = "i-limit-" + UUID.randomUUID();
try {
Response rejected = send(document, instance, 29);
assertEquals(400, rejected.statusCode());
assertEquals("ValidationException", rejected.jsonPath().getString("__type"));
assertEquals("1 validation error detected: Value '29' at 'timeoutSeconds' failed to satisfy constraint: "
+ "Member must have value greater than or equal to 30", rejected.jsonPath().getString("message"));
assertTrue(ownedCommands(instance).isEmpty());
verifyNoInteractions(executor);
Response response = send(document, instance, null);
assertEquals(200, response.statusCode());
assertEquals(3600, response.jsonPath().getInt("Command.TimeoutSeconds"));
} finally {
cleanup(instance);
}
}
@Test
void internalHookKeepsItsOneSecondBudget() {
String instance = "i-limit-" + UUID.randomUUID();
try {
RequestScopes.runAs(ACCOUNT, REGION, () -> commandService.sendCommandToInstance(instance,
"AWS-RunShellScript", Map.of("commands", List.of("echo hook")), 1, REGION));
assertEquals(1, ownedCommands(instance).size());
assertEquals(1, ownedCommands(instance).getFirst().getTimeoutSeconds());
verifyNoInteractions(executor);
} finally {
cleanup(instance);
}
}
private Response send(String document, String instance, Integer timeout) {
Map<String, Object> request = new HashMap<>(Map.of("DocumentName", document,
"InstanceIds", List.of(instance), "Parameters", Map.of("commands", List.of("echo limit"))));
if (timeout != null) {
request.put("TimeoutSeconds", timeout);
}
return call(ACCOUNT, REGION, "AmazonSSM.SendCommand", request);
}
private List<Command> ownedCommands(String instance) {
return RequestScopes.callAs(ACCOUNT, REGION,
() -> commandService.listCommands(null, instance, REGION));
}
private void cleanup(String instance) {
cleanupCommands(ACCOUNT, REGION, instance);
}
}
@@ -3,16 +3,24 @@ package io.github.hectorvent.floci.services.ssm;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import java.time.Duration;
import java.util.List;
import java.util.UUID;
import java.util.stream.Stream;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
@@ -2191,6 +2199,52 @@ class SsmIntegrationTest {
.body("RemovedLabels", contains("prod"));
}
static Stream<Arguments> malformedUnlabelScalars() {
return Stream.of(
Arguments.of("ParameterVersion", "\"1\"", "STRING_VALUE can not be converted to a Long"),
Arguments.of("ParameterVersion", "{}", "Start of structure or map found where not expected."),
Arguments.of("ParameterVersion", "[]", "Start of list found where not expected"),
Arguments.of("ParameterVersion", "true", "TRUE_VALUE can not be converted to a Long"),
Arguments.of("ParameterVersion", "false", "FALSE_VALUE can not be converted to a Long"),
Arguments.of("Name", "{}", "Start of structure or map found where not expected."),
Arguments.of("Name", "[]", "Start of list found where not expected"),
Arguments.of("Name", "5", "NUMBER_VALUE can not be converted to a String"),
Arguments.of("Labels", "[{}]", "Start of structure or map found where not expected."),
Arguments.of("Labels", "[[]]", "Start of list found where not expected"),
Arguments.of("Labels", "[5]", "NUMBER_VALUE can not be converted to a String"));
}
@ParameterizedTest
@MethodSource("malformedUnlabelScalars")
void unlabelScalarErrorsPreserveLabels(String field, String input, String expectedMessage) {
String name = "/scalar-errors/" + UUID.randomUUID();
given().header("X-Amz-Target", "AmazonSSM.PutParameter").contentType(SSM_CONTENT_TYPE)
.body("{\"Name\":\"" + name + "\",\"Type\":\"String\",\"Value\":\"original\"}")
.when().post("/").then().statusCode(200);
try {
String valid = "{\"Name\":\"" + name + "\",\"ParameterVersion\":1,\"Labels\":[\"prod\"]}";
labelParameterVersion(valid).statusCode(200);
String malformed = "{\"Name\":" + ("Name".equals(field) ? input : "\"" + name + "\"")
+ ",\"ParameterVersion\":" + ("ParameterVersion".equals(field) ? input : "1")
+ ",\"Labels\":" + ("Labels".equals(field) ? input : "[\"prod\"]") + "}";
Response rejected = unlabel(malformed).extract().response();
Response history = given().header("X-Amz-Target", "AmazonSSM.GetParameterHistory")
.contentType(SSM_CONTENT_TYPE).body("{\"Name\":\"" + name + "\"}")
.when().post("/");
assertAll("deserialization errors preserve parameter labels",
() -> assertEquals(400, rejected.statusCode()),
() -> assertEquals("SerializationException", rejected.jsonPath().getString("__type")),
() -> assertEquals(expectedMessage, rejected.jsonPath().getString("message")),
() -> assertEquals(200, history.statusCode()),
() -> assertEquals(List.of("prod"), history.jsonPath().getList("Parameters[0].Labels")));
unlabel(valid).statusCode(200).body("RemovedLabels", contains("prod"));
} finally {
given().header("X-Amz-Target", "AmazonSSM.DeleteParameter").contentType(SSM_CONTENT_TYPE)
.body("{\"Name\":\"" + name + "\"}")
.when().post("/").then().statusCode(200);
}
}
private io.restassured.response.ValidatableResponse unlabel(String body) {
return given()
.header("X-Amz-Target", "AmazonSSM.UnlabelParameterVersion")
@@ -0,0 +1,31 @@
package io.github.hectorvent.floci.services.ssm;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
class SsmJsonDeserializationTest {
private final ObjectMapper mapper = new ObjectMapper();
@ParameterizedTest
@CsvSource({
"30.0, 30",
"30.5, 30",
"-30.5, -30",
"3e1, 30",
"2147483647, 2147483647",
"2147483648, 2147483647",
"4294967326, 2147483647",
"9223372036854775808, 2147483647",
"-2147483648, -2147483648",
"-2147483649, -2147483648",
"-9223372036854775809, -2147483648",
"1e400, 2147483647",
"-1e400, -2147483648"
})
void numericValuesTruncateAndClampToTheIntegerRange(String input, int expected) throws Exception {
assertEquals(expected, SsmJsonDeserialization.optionalInteger(mapper.readTree(input), 3600));
}
}