fix(ssm): match the agent ec2messages wire format (#9431)

The stock SSM Agent polls ec2messages with the EC2WindowsMessageDeliveryService target prefix, which Floci answered with UnknownOperationException, and it reads a command payload and writes its reply as JSON text, where Floci added a Base64 layer. Floci now accepts that prefix alongside its existing one and exchanges the payload and reply as JSON text, so a stock agent can poll, run a command and report it.

Closes #9370
This commit is contained in:
James McMahon authored and GitHub committed 2026-11-25 07:52:39 -04:00
1 parent d37e445df1
commit 66f80b6a26
10 files changed
+47 -46

No files matched your search

@@ -655,7 +655,8 @@ public class ResolvedServiceCatalog {
descriptor("ec2messages", "ec2messages", config.services().ssm().enabled(), false,
null, null, 5000L, null, ServiceProtocol.JSON,
protocols(ServiceProtocol.JSON),
Set.of("AmazonSSMMessageDeliveryService."), Set.of("ec2messages"), Set.of(), Set.of()),
Set.of("AmazonSSMMessageDeliveryService.", "EC2WindowsMessageDeliveryService."),
Set.of("ec2messages"), Set.of(), Set.of()),
descriptor("ec2-instance-connect", "ec2-instance-connect", config.services().ec2instanceconnect().enabled(), false,
null, null, 5000L, null, ServiceProtocol.JSON,
protocols(ServiceProtocol.JSON),
@@ -17,7 +17,7 @@ import java.util.Map;
/**
* Handles the ec2messages internal protocol used by the amazon-ssm-agent.
*
* Operations (X-Amz-Target: AmazonSSMMessageDeliveryService.*):
* Operations (X-Amz-Target: EC2WindowsMessageDeliveryService.* or AmazonSSMMessageDeliveryService.*):
* - GetMessages — agent polls for pending commands
* - AcknowledgeMessage — agent confirms receipt
* - SendReply — agent sends command output
@@ -22,7 +22,6 @@ import org.jboss.logging.Logger;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
@@ -473,7 +472,7 @@ public class SsmCommandService implements Resettable {
LOG.debugv("AcknowledgeMessage: messageId={0} commandId={1}", messageId, commandId);
}
public void sendReply(String messageId, String payloadBase64) {
public void sendReply(String messageId, String content) {
MessageCorrelation meta = ownedCorrelation(messageId, true);
if (meta == null) {
LOG.warnv("SendReply: unknown messageId={0}", messageId);
@@ -484,8 +483,7 @@ public class SsmCommandService implements Resettable {
String region = meta.owner().region();
try {
byte[] decoded = Base64.getDecoder().decode(payloadBase64);
JsonNode payload = objectMapper.readTree(decoded);
JsonNode payload = objectMapper.readTree(content);
String status = "Success";
int returnCode = 0;
@@ -721,7 +719,7 @@ public class SsmCommandService implements Resettable {
payload.set("Parameters", params);
payload.set("DocumentContent", buildDocumentContent(documentName, parameters, timeoutSeconds));
return Base64.getEncoder().encodeToString(objectMapper.writeValueAsBytes(payload));
return objectMapper.writeValueAsString(payload);
} catch (Exception e) {
throw new RuntimeException("Failed to build command payload", e);
}
@@ -1,5 +1,5 @@
{
"_source": {"generator": "tools/aws/regen_rpcv2_cbor_shapes.py", "botocore": "botocore 1.44.9 (local/aws/botocore)", "ec2messages": "aws/amazon-ssm-agent agent/runcommand/mds/mdsservice.go blob f3e4d67147e5027ca2568d597077e56310921610"},
"_source": {"generator": "tools/aws/regen_rpcv2_cbor_shapes.py", "botocore": "botocore 1.44.9 (installed package)", "ec2messages": "aws/amazon-ssm-agent agent/runcommand/mds/mdsservice.go blob f3e4d67147e5027ca2568d597077e56310921610"},
"aliases": {
"ACM": "acm",
"AWS Marketplace Entitlement Service": "marketplace-entitlement",
@@ -69,6 +69,7 @@
"DynamoDBStreams_20120810": "dynamodbstreams",
"DynamoDB_20120810": "dynamodb",
"EC2 Instance Connect": "ec2-instance-connect",
"EC2WindowsMessageDeliveryService": "ec2messages",
"ECR": "ecr",
"ECS": "ecs",
"EMR": "emr",
@@ -14,9 +14,7 @@ import jakarta.inject.Inject;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -189,8 +187,7 @@ class SsmDirectCommandAccountIntegrationTest extends SsmCommandIntegrationFixtur
Response own = call("222222222222", "us-west-2", "AmazonSSMMessageDeliveryService.GetMessages",
Map.of("Destination", instance));
assertEquals(1, own.jsonPath().getList("Messages").size());
assertEquals(command, new ObjectMapper().readTree(Base64.getDecoder()
.decode(own.jsonPath().getString("Messages[0].Payload"))).path("CommandId").asText());
assertEquals(command, new ObjectMapper().readTree(own.jsonPath().getString("Messages[0].Payload")).path("CommandId").asText());
} finally {
deleteCommand("222222222222", "us-west-2", command, instance);
}
@@ -327,9 +324,8 @@ class SsmDirectCommandAccountIntegrationTest extends SsmCommandIntegrationFixtur
}
private static String replyPayload() {
return Base64.getEncoder().encodeToString(("{\"runtimeStatus\":{\"aws:runShellScript\":{"
+ "\"status\":\"Success\",\"code\":0,\"output\":\"owned agent output\"}}}")
.getBytes(StandardCharsets.UTF_8));
return ("{\"runtimeStatus\":{\"aws:runShellScript\":{"
+ "\"status\":\"Success\",\"code\":0,\"output\":\"owned agent output\"}}}");
}
private void assertOwnedInvocation(String account, String region, String commandId, String instance) {
@@ -12,7 +12,7 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.time.Instant;
import java.util.Base64;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;
@@ -192,7 +192,7 @@ class SsmSendCommandIntegrationTest {
@Order(7)
void agentGetsEndpoint() {
given()
.header("X-Amz-Target", "AmazonSSMMessageDeliveryService.GetEndpoint")
.header("X-Amz-Target", "EC2WindowsMessageDeliveryService.GetEndpoint")
.contentType(SSM_CT)
.body("""
{
@@ -212,7 +212,7 @@ class SsmSendCommandIntegrationTest {
@Order(8)
void agentPollsAndGetsMessage() {
given()
.header("X-Amz-Target", "AmazonSSMMessageDeliveryService.GetMessages")
.header("X-Amz-Target", "EC2WindowsMessageDeliveryService.GetMessages")
.contentType(SSM_CT)
.body("""
{
@@ -236,7 +236,7 @@ class SsmSendCommandIntegrationTest {
void agentAcknowledgesMessage() {
// First poll to get the message ID
String msgId = given()
.header("X-Amz-Target", "AmazonSSMMessageDeliveryService.GetMessages")
.header("X-Amz-Target", "EC2WindowsMessageDeliveryService.GetMessages")
.contentType(SSM_CT)
.body("""
{
@@ -270,7 +270,7 @@ class SsmSendCommandIntegrationTest {
String newCmdId = JsonPath.from(resp).getString("Command.CommandId");
msgId = given()
.header("X-Amz-Target", "AmazonSSMMessageDeliveryService.GetMessages")
.header("X-Amz-Target", "EC2WindowsMessageDeliveryService.GetMessages")
.contentType(SSM_CT)
.body("""
{
@@ -285,7 +285,7 @@ class SsmSendCommandIntegrationTest {
// Acknowledge
given()
.header("X-Amz-Target", "AmazonSSMMessageDeliveryService.AcknowledgeMessage")
.header("X-Amz-Target", "EC2WindowsMessageDeliveryService.AcknowledgeMessage")
.contentType(SSM_CT)
.body("""
{ "MessageId": "%s" }
@@ -317,7 +317,7 @@ class SsmSendCommandIntegrationTest {
// Poll
String msgId = given()
.header("X-Amz-Target", "AmazonSSMMessageDeliveryService.GetMessages")
.header("X-Amz-Target", "EC2WindowsMessageDeliveryService.GetMessages")
.contentType(SSM_CT)
.body("""
{
@@ -329,19 +329,14 @@ class SsmSendCommandIntegrationTest {
.when().post("/")
.then().statusCode(200).extract().jsonPath().getString("Messages[0].MessageId");
// Build a SendReply payload (base64 encoded agent output)
// Build the JSON-text reply produced by the agent.
String replyPayload = buildReplyPayload("world\n", "Success", 0);
// Send reply
given()
.header("X-Amz-Target", "AmazonSSMMessageDeliveryService.SendReply")
.header("X-Amz-Target", "EC2WindowsMessageDeliveryService.SendReply")
.contentType(SSM_CT)
.body("""
{
"MessageId": "%s",
"Payload": "%s"
}
""".formatted(msgId, replyPayload))
.body(Map.of("MessageId", msgId, "Payload", replyPayload))
.when()
.post("/")
.then()
@@ -466,7 +461,7 @@ class SsmSendCommandIntegrationTest {
.body("StandardOutputContent", equalTo("direct-output\n"));
given()
.header("X-Amz-Target", "AmazonSSMMessageDeliveryService.GetMessages")
.header("X-Amz-Target", "EC2WindowsMessageDeliveryService.GetMessages")
.contentType(SSM_CT)
.body("""
{
@@ -556,6 +551,6 @@ class SsmSendCommandIntegrationTest {
}
}
""".formatted(status, returnCode, stdout.replace("\n", "\\n").replace("\"", "\\\""));
return Base64.getEncoder().encodeToString(json.getBytes());
return json;
}
}
@@ -12,7 +12,6 @@ import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@@ -43,8 +42,7 @@ class SsmShellExecutionBudgetIntegrationTest extends SsmCommandIntegrationFixtur
Map.of("Destination", instance, "MessagesRequestId", "budget")));
assertEquals(200, poll.statusCode());
assertEquals(1, poll.jsonPath().getList("Messages").size());
JsonNode payload = mapper.readTree(Base64.getDecoder().decode(
poll.jsonPath().getString("Messages[0].Payload")));
JsonNode payload = mapper.readTree(poll.jsonPath().getString("Messages[0].Payload"));
JsonNode command = mapper.readTree(response.asByteArray()).path("Command");
assertAll("public metadata and delivered document",
() -> assertEquals(30, command.path("TimeoutSeconds").asInt()),
@@ -11,10 +11,8 @@ import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -93,8 +91,7 @@ class SsmShellExecutionBudgetTest {
}
List<Map<String, Object>> messages = service.getMessages("i-budget", "budget", 30);
assertEquals(1, messages.size());
JsonNode payload = mapper.readTree(new String(Base64.getDecoder().decode(
(String) messages.getFirst().get("Payload")), StandardCharsets.UTF_8));
JsonNode payload = mapper.readTree((String) messages.getFirst().get("Payload"));
assertAll("fallback retains the effective budget without changing the document default",
() -> assertEquals("3600", payload.at("/DocumentContent/parameters/executionTimeout/default")
.asText()),
@@ -129,8 +126,8 @@ class SsmShellExecutionBudgetTest {
String id = service.sendCommandToInstance("i-budget", "AWS-RunShellScript",
Map.of("commands", List.of("echo hook")), timeout, "us-east-1");
Command command = service.listCommands(id, null, "us-east-1").getFirst();
JsonNode payload = mapper.readTree(Base64.getDecoder().decode((String)
service.getMessages("i-budget", "hook", 30).getFirst().get("Payload")));
JsonNode payload = mapper.readTree((String)
service.getMessages("i-budget", "hook", 30).getFirst().get("Payload"));
assertEquals(timeout, command.getTimeoutSeconds());
assertEquals(timeout, Duration.between(command.getRequestedDateTime(), command.getExpiresAfter())
.toSeconds());
@@ -154,8 +151,8 @@ class SsmShellExecutionBudgetTest {
ObjectNode request = request(5);
request.put("DocumentName", document);
Command command = service.sendCommand(request, "us-east-1");
JsonNode payload = mapper.readTree(Base64.getDecoder().decode((String)
service.getMessages("i-budget", "other", 30).getFirst().get("Payload")));
JsonNode payload = mapper.readTree((String)
service.getMessages("i-budget", "other", 30).getFirst().get("Payload"));
assertEquals(30, Duration.between(command.getRequestedDateTime(), command.getExpiresAfter())
.toSeconds());
assertEquals("30", payload.at("/DocumentContent/parameters/executionTimeout/default").asText());
+2 -2
View File
@@ -20,7 +20,7 @@ JSON_ONLY_PREFIXES = {"DynamoDB_20111205", "CloudWatchVersion20130116"}
# Floci's JSON facades/short alias do not use the model's targetPrefix.
MODEL_ALIASES = {"AmazonApiGatewayV2": "apigatewayv2", "CloudTrail_20131101": "cloudtrail",
"SNS_20100331": "sns"}
AGENT_PREFIX = "AmazonSSMMessageDeliveryService"
AGENT_PREFIXES = ("AmazonSSMMessageDeliveryService", "EC2WindowsMessageDeliveryService")
# The agent facade has no pinned botocore model. MDS Message fields, including CreatedDate and Payload, are strings.
# aws/amazon-ssm-agent agent/runcommand/mds/mdsservice.go, immutable blob:
# https://api.github.com/repos/aws/amazon-ssm-agent/git/blobs/f3e4d67147e5027ca2568d597077e56310921610
@@ -105,7 +105,7 @@ def build(data: Path, catalog: Path, provenance: str) -> dict:
aliases.update({prefix: name for prefix, name in MODEL_ALIASES.items() if prefix in prefixes})
aliases["AWS Marketplace Entitlement Service"] = "marketplace-entitlement"
services["ec2messages"] = {"timestampFormat": "unixTimestamp", "shapes": {}, "operations": {}}
aliases[AGENT_PREFIX] = "ec2messages"
aliases.update({prefix: "ec2messages" for prefix in AGENT_PREFIXES})
missing = prefixes - aliases.keys()
if missing:
raise ValueError(f"No RPC v2 wire model for catalog prefixes: {sorted(missing)}")
+16 -1
View File
@@ -1,4 +1,19 @@
from regen_rpcv2_cbor_shapes import project_model
from regen_rpcv2_cbor_shapes import build, project_model
def test_agent_target_prefixes_share_the_string_only_wire_model(tmp_path):
data = tmp_path / "data"
data.mkdir()
catalog = tmp_path / "Catalog.java"
catalog.write_text('Set.of("AmazonSSMMessageDeliveryService.", "EC2WindowsMessageDeliveryService.")')
result = build(data, catalog, "test")
assert {prefix: result["aliases"][prefix] for prefix in (
"AmazonSSMMessageDeliveryService", "EC2WindowsMessageDeliveryService")
} == {"AmazonSSMMessageDeliveryService": "ec2messages", "EC2WindowsMessageDeliveryService": "ec2messages"}
assert result["services"]["ec2messages"] == {
"timestampFormat": "unixTimestamp", "shapes": {}, "operations": {}}
def model(shapes, operations=None, protocol="json"):