fix: support SSM PutParameter tags and ECS container healthCheck (#2567) (#3550)

* fix(ssm): support Tags and preserve tags on Overwrite in PutParameter (#2567)

* fix(ecs): round-trip containerDefinition healthCheck (#2567)

* style(ecs): replace em-dash with comma in test doc per AGENTS.md

* fix(ssm,ecs): address review feedback on description, ARN parsing and ECS healthCheck command

* test(ecs): pass HostVolumePolicy to EcsJsonHandler in healthCheck tests
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-09-13 21:23:52 -04:00
1 parent 19917ed9ed
commit 7d6e9588cd
10 files changed
+518 -4

No files matched your search

@@ -11,6 +11,7 @@ import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;
import io.github.hectorvent.floci.services.ecs.model.ContainerInstance;
import io.github.hectorvent.floci.services.ecs.model.Deployment;
import io.github.hectorvent.floci.services.ecs.model.Failure;
import io.github.hectorvent.floci.services.ecs.model.HealthCheck;
import io.github.hectorvent.floci.services.ecs.model.ContainerOverride;
import io.github.hectorvent.floci.services.ecs.model.EcsCluster;
import io.github.hectorvent.floci.services.ecs.model.EcsLoadBalancer;
@@ -1117,6 +1118,29 @@ public class EcsJsonHandler {
n.set("logConfiguration", logNode);
}
if (def.getHealthCheck() != null) {
HealthCheck hc = def.getHealthCheck();
ObjectNode hcNode = objectMapper.createObjectNode();
if (hc.command() != null) {
ArrayNode cmd = objectMapper.createArrayNode();
hc.command().forEach(cmd::add);
hcNode.set("command", cmd);
}
if (hc.interval() != null) {
hcNode.put("interval", hc.interval());
}
if (hc.timeout() != null) {
hcNode.put("timeout", hc.timeout());
}
if (hc.retries() != null) {
hcNode.put("retries", hc.retries());
}
if (hc.startPeriod() != null) {
hcNode.put("startPeriod", hc.startPeriod());
}
n.set("healthCheck", hcNode);
}
return n;
}
@@ -1419,6 +1443,9 @@ public class EcsJsonHandler {
}
def.setMountPoints(parseMountPoints(item.path("mountPoints")));
def.setLogConfiguration(parseLogConfiguration(item.path("logConfiguration")));
if (item.has("healthCheck")) {
def.setHealthCheck(parseHealthCheck(item.path("healthCheck")));
}
if (item.has("command") && item.path("command").isArray()) {
List<String> cmd = new ArrayList<>();
@@ -1503,6 +1530,21 @@ public class EcsJsonHandler {
return new LogConfiguration(logDriver, options, secretOptions);
}
private HealthCheck parseHealthCheck(JsonNode node) {
if (node == null || !node.isObject()) {
return null;
}
if (!node.hasNonNull("command") || !node.path("command").isArray() || node.path("command").isEmpty()) {
throw new AwsException("ClientException", "HealthCheck command is required.", 400);
}
List<String> command = jsonArrayToList(node.path("command"));
Integer interval = node.has("interval") ? node.path("interval").asInt() : null;
Integer timeout = node.has("timeout") ? node.path("timeout").asInt() : null;
Integer retries = node.has("retries") ? node.path("retries").asInt() : null;
Integer startPeriod = node.has("startPeriod") ? node.path("startPeriod").asInt() : null;
return new HealthCheck(command, interval, timeout, retries, startPeriod);
}
private List<Volume> parseVolumes(JsonNode node) {
List<Volume> result = new ArrayList<>();
if (!node.isArray()) {
@@ -20,6 +20,7 @@ public class ContainerDefinition {
private List<String> entryPoint;
private List<MountPoint> mountPoints;
private LogConfiguration logConfiguration;
private HealthCheck healthCheck;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
@@ -59,4 +60,7 @@ public class ContainerDefinition {
public LogConfiguration getLogConfiguration() { return logConfiguration; }
public void setLogConfiguration(LogConfiguration logConfiguration) { this.logConfiguration = logConfiguration; }
public HealthCheck getHealthCheck() { return healthCheck; }
public void setHealthCheck(HealthCheck healthCheck) { this.healthCheck = healthCheck; }
}
@@ -0,0 +1,21 @@
package io.github.hectorvent.floci.services.ecs.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
/**
* The {@code healthCheck} of an ECS container definition:
* {@code {"command": [...], "interval": ..., "timeout": ..., "retries": ..., "startPeriod": ...}}.
*
* <p>Modelled for RegisterTaskDefinition/DescribeTaskDefinition round-trip fidelity.
*/
@RegisterForReflection
public record HealthCheck(
List<String> command,
Integer interval,
Integer timeout,
Integer retries,
Integer startPeriod
) {
}
@@ -25,6 +25,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -110,7 +111,15 @@ public class SsmJsonHandler {
String description = request.has("Description") ? request.path("Description").asText() : null;
boolean overwrite = request.path("Overwrite").asBoolean(false);
long version = ssmService.putParameter(name, value, type, description, overwrite, region);
Map<String, String> tags = null;
if (request.has("Tags") && request.path("Tags").isArray()) {
tags = new LinkedHashMap<>();
for (JsonNode t : request.path("Tags")) {
tags.put(t.path("Key").asText(), t.path("Value").asText());
}
}
long version = ssmService.putParameter(name, value, type, description, overwrite, tags, region);
return Response.ok(new PutParameterResponse(version)).build();
}
@@ -155,6 +155,11 @@ public class SsmService implements ResourceProvider {
* Returns the version number.
*/
public long putParameter(String name, String value, String type, String description, boolean overwrite, String region) {
return putParameter(name, value, type, description, overwrite, null, region);
}
public long putParameter(String name, String value, String type, String description, boolean overwrite,
Map<String, String> tags, String region) {
rejectReservedName(name);
String storageKey = regionKey(region, name);
Parameter existing = parameterStore.get(storageKey).orElse(null);
@@ -165,6 +170,14 @@ public class SsmService implements ResourceProvider {
400);
}
if (overwrite && tags != null && !tags.isEmpty()) {
throw new AwsException("ValidationException",
"Invalid request: tags and overwrite can't be used together. To create a "
+ "parameter with tags, please remove overwrite flag. To update tags for an "
+ "existing parameter, please use AddTagsToResource or RemoveTagsFromResource.",
400);
}
long version = (existing != null) ? existing.getVersion() + 1 : 1;
Parameter parameter = new Parameter(name, value, type != null ? type : "String");
@@ -173,6 +186,12 @@ public class SsmService implements ResourceProvider {
parameter.setArn(regionResolver.buildArn("ssm", region, "parameter" + name));
parameter.setLastModifiedDate(Instant.now());
if (existing != null && existing.getTags() != null) {
parameter.setTags(new HashMap<>(existing.getTags()));
} else if (tags != null && !tags.isEmpty()) {
parameter.setTags(new HashMap<>(tags));
}
parameterStore.put(storageKey, parameter);
addHistory(storageKey, parameter);
@@ -356,7 +375,8 @@ public class SsmService implements ResourceProvider {
}
public void addTagsToResource(String resourceId, Map<String, String> tags, String region) {
String storageKey = regionKey(region, resourceId);
String normalizedId = normalizeResourceId(resourceId);
String storageKey = regionKey(region, normalizedId);
Parameter param = parameterStore.get(storageKey)
.orElseThrow(() -> new AwsException("InvalidResourceId",
"Resource " + resourceId + " not found.", 400));
@@ -370,7 +390,8 @@ public class SsmService implements ResourceProvider {
}
public Map<String, String> listTagsForResource(String resourceId, String region) {
String storageKey = regionKey(region, resourceId);
String normalizedId = normalizeResourceId(resourceId);
String storageKey = regionKey(region, normalizedId);
Parameter param = parameterStore.get(storageKey)
.orElseThrow(() -> new AwsException("InvalidResourceId",
"Resource " + resourceId + " not found.", 400));
@@ -378,7 +399,8 @@ public class SsmService implements ResourceProvider {
}
public void removeTagsFromResource(String resourceId, List<String> tagKeys, String region) {
String storageKey = regionKey(region, resourceId);
String normalizedId = normalizeResourceId(resourceId);
String storageKey = regionKey(region, normalizedId);
Parameter param = parameterStore.get(storageKey)
.orElseThrow(() -> new AwsException("InvalidResourceId",
"Resource " + resourceId + " not found.", 400));
@@ -392,6 +414,28 @@ public class SsmService implements ResourceProvider {
LOG.debugv("Removed tags from parameter: {0}", resourceId);
}
private static String normalizeResourceId(String resourceId) {
if (resourceId != null && resourceId.startsWith("arn:")) {
try {
AwsArnUtils.Arn arn = AwsArnUtils.parse(resourceId);
if ("ssm".equals(arn.service())) {
String resource = arn.resource();
if (resource.startsWith("parameter/")) {
return resource.substring("parameter".length());
}
if (resource.startsWith("parameter")) {
return resource.substring("parameter".length());
}
}
} catch (IllegalArgumentException e) {
// Not a valid ARN; fall through and use resourceId directly so callers
// querying parameterStore produce the standard InvalidResourceId error.
LOG.debugv("Failed to parse resourceId as ARN: {0}", resourceId);
}
}
return resourceId;
}
// ──────────────────────── Documents and Share Permissions ────────────────
// Documents live in documentStore; share state is kept alongside it in
// documentPermissionStore so callers like LZA's Custom::SSMShareDocument handler
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.ssm.model;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.quarkus.runtime.annotations.RegisterForReflection;
@@ -36,6 +37,8 @@ public class Parameter {
@JsonProperty("DataType")
private String dataType = "text";
@JsonProperty("Tags")
@JsonAlias({"tags", "Tags"})
private Map<String, String> tags = new HashMap<>();
public Parameter() {}
@@ -1239,4 +1239,30 @@ class EcsIntegrationTest {
.body("taskDefinition.containerDefinitions[1]", not(hasKey("entryPoint")))
.body("taskDefinition.containerDefinitions[1]", not(hasKey("command")));
}
@Test
@Order(71)
void registerTaskDefinitionWithHealthCheckMissingCommandReturns400() {
ecs("RegisterTaskDefinition")
.body("""
{
"family": "invalid-hc-missing-cmd",
"containerDefinitions": [
{
"name": "app",
"image": "nginx:latest",
"healthCheck": {
"interval": 30
}
}
]
}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", containsString("ClientException"))
.body("message", containsString("HealthCheck command is required."));
}
}
@@ -0,0 +1,194 @@
package io.github.hectorvent.floci.services.ecs;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.ecs.container.HostVolumePolicy;
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Unit tests for the RegisterTaskDefinition JSON wire path in {@link EcsJsonHandler}:
* container-level {@code healthCheck} must be parsed from the request, stored on the
* container definition, and serialized back in the response with the AWS wire shape,
* and must stay absent from the response when the request omitted it.
*/
class EcsJsonHandlerHealthCheckTest {
private ObjectMapper objectMapper;
private EcsJsonHandler handler;
@BeforeEach
void setUp() {
objectMapper = new ObjectMapper();
EcsService service = mock(EcsService.class);
when(service.registerTaskDefinition(anyString(), any(), any(), any(), any(), any(), any(), any(), any(), anyString()))
.thenAnswer(inv -> {
TaskDefinition td = new TaskDefinition();
td.setFamily(inv.getArgument(0));
td.setRevision(1);
td.setStatus("ACTIVE");
td.setContainerDefinitions(inv.getArgument(1, List.class));
return td;
});
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
handler = new EcsJsonHandler(service, objectMapper, new HostVolumePolicy(config));
}
@Test
void registerTaskDefinitionRoundTripsHealthCheck() throws Exception {
String requestJson = """
{
"family": "healthcheck-demo",
"containerDefinitions": [
{
"name": "app",
"image": "public.ecr.aws/docker/library/nginx:alpine",
"essential": true,
"healthCheck": {
"command": ["CMD-SHELL", "curl -f http://localhost/ || exit 1"],
"interval": 30,
"timeout": 5,
"retries": 3,
"startPeriod": 10
}
}
]
}
""";
JsonNode request = objectMapper.readTree(requestJson);
Response response = handler.handle("RegisterTaskDefinition", request, "us-east-1");
JsonNode td = objectMapper.valueToTree(response.getEntity()).path("taskDefinition");
JsonNode container = td.path("containerDefinitions").get(0);
JsonNode hc = container.path("healthCheck");
assertTrue(hc.isObject(), "healthCheck should be an object");
assertTrue(hc.path("command").isArray(), "command should be an array");
assertEquals("CMD-SHELL", hc.path("command").get(0).asText());
assertEquals("curl -f http://localhost/ || exit 1", hc.path("command").get(1).asText());
assertEquals(30, hc.path("interval").asInt());
assertEquals(5, hc.path("timeout").asInt());
assertEquals(3, hc.path("retries").asInt());
assertEquals(10, hc.path("startPeriod").asInt());
}
@Test
void registerTaskDefinitionOmitsHealthCheckWhenNotProvided() throws Exception {
String requestJson = """
{
"family": "plain-family",
"containerDefinitions": [
{
"name": "app",
"image": "alpine:latest"
}
]
}
""";
JsonNode request = objectMapper.readTree(requestJson);
Response response = handler.handle("RegisterTaskDefinition", request, "us-east-1");
JsonNode td = objectMapper.valueToTree(response.getEntity()).path("taskDefinition");
JsonNode container = td.path("containerDefinitions").get(0);
assertTrue(container.path("healthCheck").isMissingNode(),
"healthCheck must stay absent when omitted");
}
@Test
void registerTaskDefinitionHandlesPartialHealthCheckFields() throws Exception {
String requestJson = """
{
"family": "partial-hc-family",
"containerDefinitions": [
{
"name": "app",
"image": "alpine:latest",
"healthCheck": {
"command": ["CMD", "/bin/check.sh"]
}
}
]
}
""";
JsonNode request = objectMapper.readTree(requestJson);
Response response = handler.handle("RegisterTaskDefinition", request, "us-east-1");
JsonNode td = objectMapper.valueToTree(response.getEntity()).path("taskDefinition");
JsonNode container = td.path("containerDefinitions").get(0);
JsonNode hc = container.path("healthCheck");
assertTrue(hc.isObject());
assertEquals(2, hc.path("command").size());
assertEquals("CMD", hc.path("command").get(0).asText());
assertEquals("/bin/check.sh", hc.path("command").get(1).asText());
assertTrue(hc.path("interval").isMissingNode(), "interval should be absent");
assertTrue(hc.path("timeout").isMissingNode(), "timeout should be absent");
assertTrue(hc.path("retries").isMissingNode(), "retries should be absent");
assertTrue(hc.path("startPeriod").isMissingNode(), "startPeriod should be absent");
}
@Test
void registerTaskDefinitionWithMissingHealthCheckCommandThrowsClientException() throws Exception {
String requestJson = """
{
"family": "missing-hc-command",
"containerDefinitions": [
{
"name": "app",
"image": "alpine:latest",
"healthCheck": {
"interval": 30
}
}
]
}
""";
JsonNode request = objectMapper.readTree(requestJson);
AwsException ex = assertThrows(AwsException.class, () ->
handler.handle("RegisterTaskDefinition", request, "us-east-1"));
assertEquals("ClientException", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
}
@Test
void registerTaskDefinitionWithEmptyHealthCheckCommandThrowsClientException() throws Exception {
String requestJson = """
{
"family": "empty-hc-command",
"containerDefinitions": [
{
"name": "app",
"image": "alpine:latest",
"healthCheck": {
"command": []
}
}
]
}
""";
JsonNode request = objectMapper.readTree(requestJson);
AwsException ex = assertThrows(AwsException.class, () ->
handler.handle("RegisterTaskDefinition", request, "us-east-1"));
assertEquals("ClientException", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
}
}
@@ -1408,4 +1408,106 @@ class SsmIntegrationTest {
.then()
.statusCode(200);
}
@Test
@Order(17)
void putParameterWithTagsAndListTagsForResource() {
given()
.header("X-Amz-Target", "AmazonSSM.PutParameter")
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"Name": "/demo/tagged-param",
"Value": "hello",
"Type": "String",
"Tags": [
{"Key": "Project", "Value": "demo"},
{"Key": "Env", "Value": "test"}
]
}
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("Version", equalTo(1));
given()
.header("X-Amz-Target", "AmazonSSM.ListTagsForResource")
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"ResourceType": "Parameter",
"ResourceId": "/demo/tagged-param"
}
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("TagList", hasSize(2))
.body("TagList.find { it.Key == 'Project' }.Value", equalTo("demo"))
.body("TagList.find { it.Key == 'Env' }.Value", equalTo("test"));
}
@Test
@Order(18)
void putParameterOverwritePreservesExistingTags() {
given()
.header("X-Amz-Target", "AmazonSSM.PutParameter")
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"Name": "/demo/tagged-param",
"Value": "world",
"Type": "String",
"Overwrite": true
}
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("Version", equalTo(2));
given()
.header("X-Amz-Target", "AmazonSSM.ListTagsForResource")
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"ResourceType": "Parameter",
"ResourceId": "/demo/tagged-param"
}
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("TagList", hasSize(2))
.body("TagList.find { it.Key == 'Project' }.Value", equalTo("demo"));
}
@Test
@Order(19)
void putParameterOverwriteWithTagsReturns400() {
given()
.header("X-Amz-Target", "AmazonSSM.PutParameter")
.contentType(SSM_CONTENT_TYPE)
.body("""
{
"Name": "/demo/tagged-param",
"Value": "updated",
"Type": "String",
"Overwrite": true,
"Tags": [
{"Key": "Project", "Value": "demo2"}
]
}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
}
@@ -843,4 +843,73 @@ class SsmServiceTest {
assertEquals("AssociationDoesNotExist", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
}
@Test
void putParameterWithTags() {
String region = "eu-west-1";
Map<String, String> tags = Map.of("Environment", "Production", "Project", "Floci");
ssmService.putParameter("/app/tagged", "value", "String", null, false, tags, region);
Map<String, String> retrievedTags = ssmService.listTagsForResource("/app/tagged", region);
assertEquals(2, retrievedTags.size());
assertEquals("Production", retrievedTags.get("Environment"));
assertEquals("Floci", retrievedTags.get("Project"));
}
@Test
void putParameterOverwritePreservesTags() {
String region = "eu-west-1";
Map<String, String> tags = Map.of("Project", "demo");
ssmService.putParameter("/app/param", "hello", "String", null, false, tags, region);
ssmService.putParameter("/app/param", "world", "String", null, true, null, region);
Map<String, String> retrievedTags = ssmService.listTagsForResource("/app/param", region);
assertEquals(1, retrievedTags.size());
assertEquals("demo", retrievedTags.get("Project"));
}
@Test
void putParameterOverwriteWithTagsThrowsValidationException() {
String region = "eu-west-1";
Map<String, String> tags = Map.of("Project", "demo");
AwsException ex = assertThrows(AwsException.class, () ->
ssmService.putParameter("/app/conflict", "val", "String", null, true, tags, region));
assertEquals("ValidationException", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
}
@Test
void listTagsForResourceWithArnNormalized() {
String region = "eu-west-1";
Map<String, String> tags = Map.of("Project", "demo");
ssmService.putParameter("/app/arn-test", "val", "String", null, false, tags, region);
String arn = "arn:aws:ssm:" + region + ":000000000000:parameter/app/arn-test";
Map<String, String> retrievedTags = ssmService.listTagsForResource(arn, region);
assertEquals(1, retrievedTags.size());
assertEquals("demo", retrievedTags.get("Project"));
}
@Test
void listTagsForResourceWithNonAwsPartitionArnNormalized() {
String region = "us-gov-west-1";
Map<String, String> tags = Map.of("GovProject", "mission");
ssmService.putParameter("/app/gov-test", "val", "String", null, false, tags, region);
String arn = "arn:aws-us-gov:ssm:" + region + ":000000000000:parameter/app/gov-test";
Map<String, String> retrievedTags = ssmService.listTagsForResource(arn, region);
assertEquals(1, retrievedTags.size());
assertEquals("mission", retrievedTags.get("GovProject"));
}
@Test
void putParameterOverwriteClearsDescriptionWhenOmitted() {
String region = "eu-west-1";
ssmService.putParameter("/app/desc-test", "val1", "String", "Initial description", false, null, region);
assertEquals("Initial description", ssmService.getParameter("/app/desc-test", region).getDescription());
ssmService.putParameter("/app/desc-test", "val2", "String", null, true, null, region);
assertNull(ssmService.getParameter("/app/desc-test", region).getDescription());
}
}