Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(ssm): add Run Command and ec2messages agent protocol (#728)

Hector Venturaf31a07f2870d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a6c52686f7..6c19afe01d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+
+- **ssm:** Run Command — `SendCommand`, `GetCommandInvocation`, `ListCommands`, `ListCommandInvocations`, `CancelCommand`, `DescribeInstanceInformation`; `UpdateInstanceInformation` (agent registration); `ec2messages` polling protocol (`GetMessages`, `AcknowledgeMessage`, `SendReply`, `FailMessage`, `DeleteMessage`, `GetEndpoint`) so the real `amazon-ssm-agent` running inside EC2 containers can register, receive commands, and report output
+
## [1.5.12] - 2026-05-04
### Added
diff --git a/README.md b/README.md
index e08736ae6f..a6cc3865d6 100644
--- a/README.md
+++ b/README.md
@@ -72,6 +72,7 @@
| CodeBuild (real Docker build execution, S3 artifacts, CloudWatch logs) | ✅ | ❌ |
| CodeDeploy (Lambda traffic shifting, lifecycle hooks, auto-rollback) | ✅ | ❌ |
| Auto Scaling (groups, launch configs, reconciler, ELB v2 integration) | ✅ | ❌ |
+| SSM Run Command (SendCommand + real agent polling via ec2messages) | ✅ | ❌ |
| Native binary | ✅ ~40 MB | ❌ |
**Broad AWS coverage. Free forever.**
@@ -208,6 +209,7 @@ All default images are configurable via environment variables, useful for pinnin
| Service | How it works | Notable features |
|---|---|---|
| **SSM Parameter Store** | In-process | Version history, labels, SecureString, tagging |
+| **SSM Run Command** | In-process | `SendCommand`, `GetCommandInvocation`, `ListCommands`, `CancelCommand`; `DescribeInstanceInformation`; `ec2messages` polling protocol so the real `amazon-ssm-agent` running inside EC2 containers can register, receive commands, and report output |
| **SQS** | In-process | Standard & FIFO, DLQ, visibility timeout, batch, tagging |
| **SNS** | In-process | Topics, subscriptions, SQS / Lambda / HTTP delivery, tagging |
| **S3** | In-process | Versioning, multipart upload, pre-signed URLs, Object Lock, event notifications |
@@ -254,7 +256,7 @@ All default images are configurable via environment variables, useful for pinnin
>
> For per-service operation counts and endpoint protocols, see the [Services Overview](https://floci.io/floci/services/) in the documentation site.
-**42 AWS services supported.**
+**43 AWS services supported.**
## Persistence & Storage Modes
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 c783ba7ee0..34dc38be2a 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
@@ -18,6 +18,7 @@ import io.github.hectorvent.floci.services.eventbridge.EventBridgeHandler;
import io.github.hectorvent.floci.services.kinesis.KinesisJsonHandler;
import io.github.hectorvent.floci.services.kms.KmsJsonHandler;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerJsonHandler;
+import io.github.hectorvent.floci.services.ssm.Ec2MessagesJsonHandler;
import io.github.hectorvent.floci.services.ssm.SsmJsonHandler;
import jakarta.inject.Inject;
import jakarta.ws.rs.*;
@@ -60,6 +61,7 @@ public class AwsJson11Controller {
private final ResourceGroupsTaggingJsonHandler resourceGroupsTaggingJsonHandler;
private final CodeBuildJsonHandler codeBuildJsonHandler;
private final CodeDeployJsonHandler codeDeployJsonHandler;
+ private final Ec2MessagesJsonHandler ec2MessagesJsonHandler;
@Inject
public AwsJson11Controller(ObjectMapper objectMapper, ResolvedServiceCatalog catalog,
@@ -76,7 +78,8 @@ public class AwsJson11Controller {
FirehoseJsonHandler firehoseJsonHandler,
ResourceGroupsTaggingJsonHandler resourceGroupsTaggingJsonHandler,
CodeBuildJsonHandler codeBuildJsonHandler,
- CodeDeployJsonHandler codeDeployJsonHandler) {
+ CodeDeployJsonHandler codeDeployJsonHandler,
+ Ec2MessagesJsonHandler ec2MessagesJsonHandler) {
this.objectMapper = objectMapper;
this.catalog = catalog;
this.regionResolver = regionResolver;
@@ -97,6 +100,7 @@ public class AwsJson11Controller {
this.resourceGroupsTaggingJsonHandler = resourceGroupsTaggingJsonHandler;
this.codeBuildJsonHandler = codeBuildJsonHandler;
this.codeDeployJsonHandler = codeDeployJsonHandler;
+ this.ec2MessagesJsonHandler = ec2MessagesJsonHandler;
}
@POST
@@ -142,6 +146,7 @@ public class AwsJson11Controller {
case "tagging" -> resourceGroupsTaggingJsonHandler.handle(action, request, region);
case "codebuild" -> codeBuildJsonHandler.handle(action, request, region, regionResolver.getAccountId());
case "codedeploy" -> codeDeployJsonHandler.handle(action, request, region);
+ case "ec2messages" -> ec2MessagesJsonHandler.handle(action, request, region);
default -> null;
};
// catalog.matchTarget is protocol-agnostic: a JSON 1.0 target
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
index 0d2dbf8796..24732cf0b0 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
@@ -220,7 +220,11 @@ public class ResolvedServiceCatalog {
descriptor("autoscaling", "autoscaling", config.services().autoscaling().enabled(), true,
"autoscaling", config.storage().mode(), 5000L, AwsNamespaces.AUTOSCALING, ServiceProtocol.QUERY,
protocols(ServiceProtocol.QUERY),
- Set.of(), Set.of("autoscaling"), Set.of(), Set.of())
+ Set.of(), Set.of("autoscaling"), Set.of(), Set.of()),
+ 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())
));
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ssm/Ec2MessagesJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/ssm/Ec2MessagesJsonHandler.java
new file mode 100644
index 0000000000..ccbef5cdd4
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ssm/Ec2MessagesJsonHandler.java
@@ -0,0 +1,114 @@
+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.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.core.common.AwsErrorResponse;
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.core.Response;
+import org.jboss.logging.Logger;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Handles the ec2messages internal protocol used by the amazon-ssm-agent.
+ *
+ * Operations (X-Amz-Target: AmazonSSMMessageDeliveryService.*):
+ * - GetMessages — agent polls for pending commands
+ * - AcknowledgeMessage — agent confirms receipt
+ * - SendReply — agent sends command output
+ * - FailMessage — agent reports processing failure
+ * - DeleteMessage — agent discards a message
+ * - GetEndpoint — agent discovers the service endpoint
+ */
+@ApplicationScoped
+public class Ec2MessagesJsonHandler {
+
+ private static final Logger LOG = Logger.getLogger(Ec2MessagesJsonHandler.class);
+
+ private final SsmCommandService commandService;
+ private final ObjectMapper objectMapper;
+ private final EmulatorConfig config;
+
+ @Inject
+ public Ec2MessagesJsonHandler(SsmCommandService commandService, ObjectMapper objectMapper, EmulatorConfig config) {
+ this.commandService = commandService;
+ this.objectMapper = objectMapper;
+ this.config = config;
+ }
+
+ public Response handle(String action, JsonNode request, String region) {
+ return switch (action) {
+ case "GetMessages" -> handleGetMessages(request, region);
+ case "AcknowledgeMessage" -> handleAcknowledgeMessage(request);
+ case "SendReply" -> handleSendReply(request);
+ case "FailMessage" -> handleFailMessage(request);
+ case "DeleteMessage" -> handleDeleteMessage(request);
+ case "GetEndpoint" -> handleGetEndpoint(request, region);
+ default -> Response.status(400)
+ .entity(new AwsErrorResponse("UnsupportedOperation", "Operation " + action + " is not supported."))
+ .build();
+ };
+ }
+
+ private Response handleGetMessages(JsonNode request, String region) {
+ String destination = request.path("Destination").asText();
+ String messagesRequestId = request.path("MessagesRequestId").asText("");
+ int visibilityTimeout = request.path("VisibilityTimeoutInSeconds").asInt(30);
+
+ List<Map<String, Object>> messages = commandService.getMessages(destination, messagesRequestId, visibilityTimeout);
+
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode messagesArray = objectMapper.createArrayNode();
+ for (Map<String, Object> msg : messages) {
+ ObjectNode msgNode = objectMapper.createObjectNode();
+ msg.forEach((k, v) -> msgNode.put(k, v.toString()));
+ messagesArray.add(msgNode);
+ }
+ response.set("Messages", messagesArray);
+ return Response.ok(response).build();
+ }
+
+ private Response handleAcknowledgeMessage(JsonNode request) {
+ String messageId = request.path("MessageId").asText();
+ commandService.acknowledgeMessage(messageId);
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ private Response handleSendReply(JsonNode request) {
+ String messageId = request.path("MessageId").asText();
+ String payload = request.path("Payload").asText();
+ commandService.sendReply(messageId, payload);
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ private Response handleFailMessage(JsonNode request) {
+ String messageId = request.path("MessageId").asText();
+ String failureType = request.path("FailureType").asText("InternalError");
+ commandService.failMessage(messageId, failureType);
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ private Response handleDeleteMessage(JsonNode request) {
+ String messageId = request.path("MessageId").asText();
+ commandService.deleteMessage(messageId);
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ private Response handleGetEndpoint(JsonNode request, String region) {
+ String protocol = request.path("Protocol").asText("ec2messages");
+ String endpoint = config.effectiveBaseUrl();
+
+ ObjectNode endpointNode = objectMapper.createObjectNode();
+ endpointNode.put("Protocol", protocol);
+ endpointNode.put("Endpoint", endpoint);
+
+ ObjectNode response = objectMapper.createObjectNode();
+ response.set("Endpoint", endpointNode);
+ return Response.ok(response).build();
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ssm/SsmCommandService.java b/src/main/java/io/github/hectorvent/floci/services/ssm/SsmCommandService.java
new file mode 100644
index 0000000000..199d02df92
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ssm/SsmCommandService.java
@@ -0,0 +1,528 @@
+package io.github.hectorvent.floci.services.ssm;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.core.storage.StorageBackend;
+import io.github.hectorvent.floci.core.storage.StorageFactory;
+import io.github.hectorvent.floci.services.ssm.model.Command;
+import io.github.hectorvent.floci.services.ssm.model.CommandInvocation;
+import io.github.hectorvent.floci.services.ssm.model.InstanceInformation;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Queue;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentLinkedQueue;
+
+/**
+ * Handles SSM agent registration and command execution lifecycle:
+ * - UpdateInstanceInformation (agent side, via AmazonSSM target)
+ * - SendCommand / GetCommandInvocation / ListCommands / ListCommandInvocations / CancelCommand (public API)
+ * - GetMessages / AcknowledgeMessage / SendReply / FailMessage / DeleteMessage (ec2messages, agent side)
+ */
+@ApplicationScoped
+public class SsmCommandService {
+
+ private static final Logger LOG = Logger.getLogger(SsmCommandService.class);
+ private static final int MAX_OUTPUT_CHARS = 24000;
+
+ private final StorageBackend<String, InstanceInformation> instanceStore;
+ private final StorageBackend<String, Command> commandStore;
+ private final StorageBackend<String, CommandInvocation> invocationStore;
+ private final ObjectMapper objectMapper;
+ private final RegionResolver regionResolver;
+
+ // In-memory queues: instanceId → pending messages. Not persisted — lost on restart.
+ private final ConcurrentHashMap<String, Queue<PendingMessage>> messageQueues = new ConcurrentHashMap<>();
+ // messageId → (commandId, instanceId) for correlating SendReply back to an invocation
+ private final ConcurrentHashMap<String, String[]> messageIndex = new ConcurrentHashMap<>();
+
+ @Inject
+ public SsmCommandService(StorageFactory storageFactory, ObjectMapper objectMapper, RegionResolver regionResolver) {
+ this.instanceStore = storageFactory.create("ssm", "ssm-instances.json", new TypeReference<>() {});
+ this.commandStore = storageFactory.create("ssm", "ssm-commands.json", new TypeReference<>() {});
+ this.invocationStore = storageFactory.create("ssm", "ssm-invocations.json", new TypeReference<>() {});
+ this.objectMapper = objectMapper;
+ this.regionResolver = regionResolver;
+ }
+
+ // ── Agent registration ──────────────────────────────────────────────────
+
+ public void updateInstanceInformation(JsonNode request, String region) {
+ String instanceId = request.path("InstanceId").asText("");
+ if (instanceId.isEmpty()) {
+ // Some older agent versions don't send InstanceId; fall back to a generated key
+ instanceId = "mi-" + UUID.randomUUID().toString().replace("-", "").substring(0, 17);
+ }
+
+ InstanceInformation info = instanceStore.get(instanceKey(region, instanceId))
+ .orElse(new InstanceInformation());
+
+ info.setInstanceId(instanceId);
+ info.setAgentName(request.path("AgentName").asText("amazon-ssm-agent"));
+ info.setAgentVersion(request.path("AgentVersion").asText("3.0.0.0"));
+ info.setPingStatus("Online");
+ info.setLastPingDateTime(Instant.now());
+ info.setPlatformType(request.path("PlatformType").asText("Linux"));
+ info.setPlatformName(request.path("PlatformName").asText(""));
+ info.setPlatformVersion(request.path("PlatformVersion").asText(""));
+ info.setIpAddress(request.path("IPAddress").asText(""));
+ info.setComputerName(request.path("Hostname").asText(instanceId));
+ info.setRegion(region);
+
+ if (info.getRegistrationDate() == null) {
+ info.setRegistrationDate(Instant.now());
+ }
+
+ instanceStore.put(instanceKey(region, instanceId), info);
+ LOG.infov("SSM agent registered: instanceId={0} platform={1}/{2}", instanceId, info.getPlatformType(), info.getPlatformName());
+ }
+
+ public List<InstanceInformation> describeInstanceInformation(String region) {
+ String prefix = region + "::";
+ return instanceStore.scan(k -> k.startsWith(prefix));
+ }
+
+ // ── Public SendCommand API ──────────────────────────────────────────────
+
+ public Command sendCommand(JsonNode request, String region) {
+ String documentName = request.path("DocumentName").asText();
+ if (documentName.isEmpty()) {
+ throw new AwsException("InvalidDocument", "DocumentName is required.", 400);
+ }
+
+ List<String> instanceIds = new ArrayList<>();
+ request.path("InstanceIds").forEach(n -> instanceIds.add(n.asText()));
+ if (instanceIds.isEmpty()) {
+ throw new AwsException("InvalidInstanceId", "At least one InstanceId is required.", 400);
+ }
+
+ Map<String, List<String>> parameters = parseParameters(request.path("Parameters"));
+ String comment = request.path("Comment").asText("");
+ int timeoutSeconds = request.path("TimeoutSeconds").asInt(3600);
+ String documentVersion = request.path("DocumentVersion").asText("$DEFAULT");
+ String outputS3Bucket = request.path("OutputS3BucketName").asText("");
+ String outputS3Prefix = request.path("OutputS3KeyPrefix").asText("");
+
+ String commandId = UUID.randomUUID().toString();
+ Instant now = Instant.now();
+
+ Command command = new Command();
+ command.setCommandId(commandId);
+ command.setDocumentName(documentName);
+ command.setDocumentVersion(documentVersion);
+ command.setComment(comment);
+ command.setParameters(parameters);
+ command.setInstanceIds(new ArrayList<>(instanceIds));
+ command.setRequestedDateTime(now);
+ command.setStatus("Pending");
+ command.setStatusDetails("Pending");
+ command.setTimeoutSeconds(timeoutSeconds);
+ command.setTargetCount(instanceIds.size());
+ command.setOutputS3BucketName(outputS3Bucket.isEmpty() ? null : outputS3Bucket);
+ command.setOutputS3KeyPrefix(outputS3Prefix.isEmpty() ? null : outputS3Prefix);
+ command.setOutputS3Region(region);
+ command.setRegion(region);
+ command.setExpiresAfter(now.plusSeconds(timeoutSeconds));
+
+ commandStore.put(commandKey(region, commandId), command);
+
+ // Create invocations and queue messages for each target instance
+ for (String instanceId : instanceIds) {
+ CommandInvocation inv = new CommandInvocation();
+ inv.setCommandId(commandId);
+ inv.setInstanceId(instanceId);
+ inv.setComment(comment);
+ inv.setDocumentName(documentName);
+ inv.setDocumentVersion(documentVersion);
+ inv.setRequestedDateTime(now);
+ inv.setStatus("Pending");
+ inv.setStatusDetails("Pending");
+ inv.setRegion(region);
+ invocationStore.put(invocationKey(region, commandId, instanceId), inv);
+
+ queueMessage(commandId, instanceId, documentName, parameters, timeoutSeconds, region);
+ }
+
+ // Transition command to InProgress since messages are queued
+ command.setStatus("InProgress");
+ command.setStatusDetails("InProgress");
+ commandStore.put(commandKey(region, commandId), command);
+
+ LOG.infov("SendCommand: commandId={0} document={1} targets={2}", commandId, documentName, instanceIds);
+ return command;
+ }
+
+ public CommandInvocation getCommandInvocation(String commandId, String instanceId, String region) {
+ return invocationStore.get(invocationKey(region, commandId, instanceId))
+ .orElseThrow(() -> new AwsException("InvocationDoesNotExist",
+ "Command " + commandId + " on instance " + instanceId + " does not exist.", 400));
+ }
+
+ public List<Command> listCommands(String commandId, String instanceId, String region) {
+ String prefix = region + "::";
+ return commandStore.scan(k -> {
+ if (!k.startsWith(prefix)) return false;
+ if (commandId != null && !k.equals(commandKey(region, commandId))) return false;
+ if (instanceId != null) {
+ Command cmd = commandStore.get(k).orElse(null);
+ return cmd != null && cmd.getInstanceIds() != null && cmd.getInstanceIds().contains(instanceId);
+ }
+ return true;
+ });
+ }
+
+ public List<CommandInvocation> listCommandInvocations(String commandId, String instanceId, String region) {
+ String prefix = region + "::";
+ return invocationStore.scan(k -> {
+ if (!k.startsWith(prefix)) return false;
+ if (commandId != null && !k.contains("::" + commandId + "::")) return false;
+ if (instanceId != null && !k.endsWith("::" + instanceId)) return false;
+ return true;
+ });
+ }
+
+ public void cancelCommand(String commandId, List<String> targetInstanceIds, String region) {
+ Command command = commandStore.get(commandKey(region, commandId))
+ .orElseThrow(() -> new AwsException("InvalidCommandId",
+ "Command " + commandId + " does not exist.", 400));
+
+ List<String> targets = (targetInstanceIds != null && !targetInstanceIds.isEmpty())
+ ? targetInstanceIds
+ : command.getInstanceIds();
+
+ for (String instanceId : targets) {
+ String invKey = invocationKey(region, commandId, instanceId);
+ invocationStore.get(invKey).ifPresent(inv -> {
+ if ("Pending".equals(inv.getStatus()) || "InProgress".equals(inv.getStatus())) {
+ inv.setStatus("Cancelled");
+ inv.setStatusDetails("Cancelled");
+ invocationStore.put(invKey, inv);
+ }
+ // Remove any queued (not-yet-polled) messages for this instance
+ Queue<PendingMessage> q = messageQueues.get(instanceId);
+ if (q != null) {
+ q.removeIf(m -> m.commandId().equals(commandId));
+ }
+ });
+ }
+
+ command.setStatus("Cancelled");
+ command.setStatusDetails("Cancelled");
+ commandStore.put(commandKey(region, commandId), command);
+ LOG.infov("CancelCommand: commandId={0}", commandId);
+ }
+
+ // ── ec2messages agent protocol ──────────────────────────────────────────
+
+ public List<Map<String, Object>> getMessages(String instanceId, String messagesRequestId, int visibilityTimeout) {
+ Queue<PendingMessage> queue = messageQueues.get(instanceId);
+ List<Map<String, Object>> result = new ArrayList<>();
+ if (queue == null || queue.isEmpty()) {
+ return result;
+ }
+
+ PendingMessage msg = queue.poll();
+ if (msg == null) {
+ return result;
+ }
+
+ // Track for AcknowledgeMessage / SendReply correlation
+ messageIndex.put(msg.messageId(), new String[]{msg.commandId(), instanceId, msg.region()});
+
+ result.add(Map.of(
+ "MessageId", msg.messageId(),
+ "Destination", instanceId,
+ "CreatedDate", msg.createdDate().toString(),
+ "Topic", "aws.ssm.sendCommand." + msg.region(),
+ "Payload", msg.payload()
+ ));
+
+ LOG.infov("GetMessages: instanceId={0} returned messageId={1}", instanceId, msg.messageId());
+ return result;
+ }
+
+ public void acknowledgeMessage(String messageId) {
+ // Message was already removed from queue on GetMessages. Just update invocation to InProgress.
+ String[] meta = messageIndex.get(messageId);
+ if (meta == null) {
+ return;
+ }
+ String commandId = meta[0];
+ String instanceId = meta[1];
+ String region = meta[2];
+
+ String invKey = invocationKey(region, commandId, instanceId);
+ invocationStore.get(invKey).ifPresent(inv -> {
+ if ("Pending".equals(inv.getStatus())) {
+ inv.setStatus("InProgress");
+ inv.setStatusDetails("InProgress");
+ inv.setExecutionStartDateTime(Instant.now());
+ invocationStore.put(invKey, inv);
+ }
+ });
+ LOG.debugv("AcknowledgeMessage: messageId={0} commandId={1}", messageId, commandId);
+ }
+
+ public void sendReply(String messageId, String payloadBase64) {
+ String[] meta = messageIndex.remove(messageId);
+ if (meta == null) {
+ LOG.warnv("SendReply: unknown messageId={0}", messageId);
+ return;
+ }
+ String commandId = meta[0];
+ String instanceId = meta[1];
+ String region = meta[2];
+
+ try {
+ byte[] decoded = Base64.getDecoder().decode(payloadBase64);
+ JsonNode payload = objectMapper.readTree(decoded);
+
+ String status = "Success";
+ int returnCode = 0;
+ String stdout = "";
+ String stderr = "";
+ Instant endTime = Instant.now();
+
+ // Parse runtimeStatus or pluginResults — take the first plugin entry found
+ JsonNode statusNode = payload.has("runtimeStatus") ? payload.get("runtimeStatus")
+ : payload.get("pluginResults");
+ if (statusNode != null && statusNode.isObject()) {
+ Iterator<Map.Entry<String, JsonNode>> it = statusNode.fields();
+ if (it.hasNext()) {
+ JsonNode plugin = it.next().getValue();
+ status = plugin.path("status").asText("Success");
+ returnCode = plugin.path("returnCode").asInt(plugin.path("code").asInt(0));
+ stdout = plugin.path("standardOutput").asText(plugin.path("output").asText(""));
+ stderr = plugin.path("standardError").asText("");
+ }
+ }
+
+ // Trim output to AWS limits
+ if (stdout.length() > MAX_OUTPUT_CHARS) {
+ stdout = stdout.substring(stdout.length() - MAX_OUTPUT_CHARS);
+ }
+ if (stderr.length() > MAX_OUTPUT_CHARS) {
+ stderr = stderr.substring(stderr.length() - MAX_OUTPUT_CHARS);
+ }
+
+ String invKey = invocationKey(region, commandId, instanceId);
+ CommandInvocation inv = invocationStore.get(invKey).orElse(null);
+ if (inv != null) {
+ inv.setStatus(toInvocationStatus(status));
+ inv.setStatusDetails(toInvocationStatus(status));
+ inv.setStandardOutputContent(stdout);
+ inv.setStandardErrorContent(stderr);
+ inv.setResponseCode(returnCode);
+ inv.setExecutionEndDateTime(endTime);
+ invocationStore.put(invKey, inv);
+ }
+
+ // Recalculate command status
+ updateCommandStatus(commandId, region);
+ LOG.infov("SendReply: commandId={0} instanceId={1} status={2} rc={3}", commandId, instanceId, status, returnCode);
+ } catch (Exception e) {
+ LOG.warnv(e, "Failed to parse SendReply payload for messageId={0}", messageId);
+ }
+ }
+
+ public void failMessage(String messageId, String failureType) {
+ String[] meta = messageIndex.remove(messageId);
+ if (meta == null) {
+ return;
+ }
+ String commandId = meta[0];
+ String instanceId = meta[1];
+ String region = meta[2];
+
+ String invKey = invocationKey(region, commandId, instanceId);
+ invocationStore.get(invKey).ifPresent(inv -> {
+ inv.setStatus("Failed");
+ inv.setStatusDetails("Failed: " + failureType);
+ inv.setExecutionEndDateTime(Instant.now());
+ invocationStore.put(invKey, inv);
+ });
+ updateCommandStatus(commandId, region);
+ LOG.warnv("FailMessage: commandId={0} instanceId={1} failureType={2}", commandId, instanceId, failureType);
+ }
+
+ public void deleteMessage(String messageId) {
+ messageIndex.remove(messageId);
+ }
+
+ // ── Internal helpers ────────────────────────────────────────────────────
+
+ private void queueMessage(String commandId, String instanceId, String documentName,
+ Map<String, List<String>> parameters, int timeoutSeconds, String region) {
+ String messageId = UUID.randomUUID().toString();
+ String payload = buildCommandPayload(commandId, documentName, documentVersion(parameters), parameters, timeoutSeconds, region);
+ PendingMessage msg = new PendingMessage(messageId, commandId, region, Instant.now(), payload);
+ messageQueues.computeIfAbsent(instanceId, k -> new ConcurrentLinkedQueue<>()).add(msg);
+ }
+
+ private String buildCommandPayload(String commandId, String documentName, String docVersion,
+ Map<String, List<String>> parameters, int timeoutSeconds, String region) {
+ try {
+ ObjectNode payload = objectMapper.createObjectNode();
+ payload.put("DocumentName", documentName);
+ payload.put("DocumentVersion", docVersion);
+ payload.put("CommandId", commandId);
+ payload.put("OutputS3BucketName", "");
+ payload.put("OutputS3KeyPrefix", "");
+ payload.put("OutputS3Region", region);
+ payload.put("CloudWatchLogGroupName", "");
+ payload.put("CloudWatchLogStreamName", "");
+
+ ObjectNode params = objectMapper.createObjectNode();
+ if (parameters != null) {
+ for (Map.Entry<String, List<String>> e : parameters.entrySet()) {
+ ArrayNode arr = objectMapper.createArrayNode();
+ e.getValue().forEach(arr::add);
+ params.set(e.getKey(), arr);
+ }
+ }
+ payload.set("Parameters", params);
+ payload.set("DocumentContent", buildDocumentContent(documentName, parameters, timeoutSeconds));
+
+ return Base64.getEncoder().encodeToString(objectMapper.writeValueAsBytes(payload));
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to build command payload", e);
+ }
+ }
+
+ private JsonNode buildDocumentContent(String documentName, Map<String, List<String>> parameters, int timeoutSeconds) {
+ ObjectNode doc = objectMapper.createObjectNode();
+ doc.put("schemaVersion", "2.2");
+ doc.put("description", documentName);
+
+ ObjectNode docParams = objectMapper.createObjectNode();
+ ObjectNode commandsParam = objectMapper.createObjectNode();
+ commandsParam.put("type", "StringList");
+ commandsParam.put("description", "Commands to run.");
+ docParams.set("commands", commandsParam);
+
+ ObjectNode wdParam = objectMapper.createObjectNode();
+ wdParam.put("type", "String");
+ wdParam.put("default", "");
+ wdParam.put("description", "Working directory.");
+ docParams.set("workingDirectory", wdParam);
+
+ ObjectNode toParam = objectMapper.createObjectNode();
+ toParam.put("type", "String");
+ toParam.put("default", String.valueOf(timeoutSeconds));
+ toParam.put("description", "Execution timeout in seconds.");
+ docParams.set("executionTimeout", toParam);
+ doc.set("parameters", docParams);
+
+ ArrayNode mainSteps = objectMapper.createArrayNode();
+ ObjectNode step = objectMapper.createObjectNode();
+ step.put("action", resolveAction(documentName));
+ step.put("name", "runShellScript");
+ ObjectNode inputs = objectMapper.createObjectNode();
+ inputs.put("runCommand", "{{ commands }}");
+ inputs.put("workingDirectory", "{{ workingDirectory }}");
+ inputs.put("timeoutSeconds", "{{ executionTimeout }}");
+ step.set("inputs", inputs);
+ mainSteps.add(step);
+ doc.set("mainSteps", mainSteps);
+
+ return doc;
+ }
+
+ private String resolveAction(String documentName) {
+ return switch (documentName) {
+ case "AWS-RunPowerShellScript" -> "aws:runPowerShellScript";
+ default -> "aws:runShellScript";
+ };
+ }
+
+ private String documentVersion(Map<String, List<String>> parameters) {
+ return "$DEFAULT";
+ }
+
+ private void updateCommandStatus(String commandId, String region) {
+ Command command = commandStore.get(commandKey(region, commandId)).orElse(null);
+ if (command == null) {
+ return;
+ }
+
+ List<String> instanceIds = command.getInstanceIds();
+ int completed = 0;
+ int errors = 0;
+ boolean anyInProgress = false;
+
+ for (String iid : instanceIds) {
+ CommandInvocation inv = invocationStore.get(invocationKey(region, commandId, iid)).orElse(null);
+ if (inv == null) continue;
+ String s = inv.getStatus();
+ if ("Success".equals(s)) {
+ completed++;
+ } else if ("Failed".equals(s) || "TimedOut".equals(s) || "Cancelled".equals(s)) {
+ completed++;
+ errors++;
+ } else if ("InProgress".equals(s) || "Pending".equals(s)) {
+ anyInProgress = true;
+ }
+ }
+
+ command.setCompletedCount(completed);
+ command.setErrorCount(errors);
+
+ if (!anyInProgress && completed == instanceIds.size()) {
+ command.setStatus(errors == 0 ? "Success" : (errors == instanceIds.size() ? "Failed" : "Success"));
+ command.setStatusDetails(command.getStatus());
+ }
+
+ commandStore.put(commandKey(region, commandId), command);
+ }
+
+ private static String toInvocationStatus(String agentStatus) {
+ return switch (agentStatus) {
+ case "Success" -> "Success";
+ case "Failed" -> "Failed";
+ case "TimedOut" -> "TimedOut";
+ case "Cancelled", "Canceled" -> "Cancelled";
+ default -> "Failed";
+ };
+ }
+
+ @SuppressWarnings("unchecked")
+ private Map<String, List<String>> parseParameters(JsonNode parametersNode) {
+ if (parametersNode == null || parametersNode.isNull() || !parametersNode.isObject()) {
+ return Map.of();
+ }
+ try {
+ return objectMapper.convertValue(parametersNode,
+ new TypeReference<Map<String, List<String>>>() {});
+ } catch (Exception e) {
+ return Map.of();
+ }
+ }
+
+ private static String instanceKey(String region, String instanceId) {
+ return region + "::" + instanceId;
+ }
+
+ private static String commandKey(String region, String commandId) {
+ return region + "::" + commandId;
+ }
+
+ private static String invocationKey(String region, String commandId, String instanceId) {
+ return region + "::" + commandId + "::" + instanceId;
+ }
+
+ record PendingMessage(String messageId, String commandId, String region, Instant createdDate, String payload) {}
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ssm/SsmJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/ssm/SsmJsonHandler.java
index 3a9d23b22e..577b228c15 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ssm/SsmJsonHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ssm/SsmJsonHandler.java
@@ -1,6 +1,9 @@
package io.github.hectorvent.floci.services.ssm;
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
+import io.github.hectorvent.floci.services.ssm.model.Command;
+import io.github.hectorvent.floci.services.ssm.model.CommandInvocation;
+import io.github.hectorvent.floci.services.ssm.model.InstanceInformation;
import io.github.hectorvent.floci.services.ssm.model.Parameter;
import io.github.hectorvent.floci.services.ssm.model.ParameterHistory;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -22,16 +25,19 @@ import java.util.Map;
public class SsmJsonHandler {
private final SsmService ssmService;
+ private final SsmCommandService commandService;
private final ObjectMapper objectMapper;
@Inject
- public SsmJsonHandler(SsmService ssmService, ObjectMapper objectMapper) {
+ public SsmJsonHandler(SsmService ssmService, SsmCommandService commandService, ObjectMapper objectMapper) {
this.ssmService = ssmService;
+ this.commandService = commandService;
this.objectMapper = objectMapper;
}
public Response handle(String action, JsonNode request, String region) {
return switch (action) {
+ // Parameter Store
case "PutParameter" -> handlePutParameter(request, region);
case "GetParameter" -> handleGetParameter(request, region);
case "GetParameters" -> handleGetParameters(request, region);
@@ -44,6 +50,15 @@ public class SsmJsonHandler {
case "AddTagsToResource" -> handleAddTagsToResource(request, region);
case "ListTagsForResource" -> handleListTagsForResource(request, region);
case "RemoveTagsFromResource" -> handleRemoveTagsFromResource(request, region);
+ // Run Command (public API)
+ case "SendCommand" -> handleSendCommand(request, region);
+ case "GetCommandInvocation" -> handleGetCommandInvocation(request, region);
+ case "ListCommands" -> handleListCommands(request, region);
+ case "ListCommandInvocations" -> handleListCommandInvocations(request, region);
+ case "CancelCommand" -> handleCancelCommand(request, region);
+ case "DescribeInstanceInformation" -> handleDescribeInstanceInformation(request, region);
+ // Agent registration (internal, not in public SDK)
+ case "UpdateInstanceInformation" -> handleUpdateInstanceInformation(request, region);
default -> Response.status(400)
.entity(new AwsErrorResponse("UnsupportedOperation", "Operation " + action + " is not supported."))
.build();
@@ -245,4 +260,150 @@ public class SsmJsonHandler {
node.put("DataType", p.getDataType());
return node;
}
+
+ // ── Agent registration ─────────────────────────────────────────────────
+
+ private Response handleUpdateInstanceInformation(JsonNode request, String region) {
+ commandService.updateInstanceInformation(request, region);
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ // ── Run Command public API ─────────────────────────────────────────────
+
+ private Response handleSendCommand(JsonNode request, String region) {
+ Command command = commandService.sendCommand(request, region);
+ ObjectNode response = objectMapper.createObjectNode();
+ response.set("Command", commandToNode(command));
+ return Response.ok(response).build();
+ }
+
+ private Response handleGetCommandInvocation(JsonNode request, String region) {
+ String commandId = request.path("CommandId").asText();
+ String instanceId = request.path("InstanceId").asText();
+ CommandInvocation inv = commandService.getCommandInvocation(commandId, instanceId, region);
+ return Response.ok(invocationToDetailNode(inv)).build();
+ }
+
+ private Response handleListCommands(JsonNode request, String region) {
+ String commandId = request.has("CommandId") ? request.path("CommandId").asText() : null;
+ String instanceId = request.has("InstanceId") ? request.path("InstanceId").asText() : null;
+ List<Command> commands = commandService.listCommands(commandId, instanceId, region);
+
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode commandsArray = objectMapper.createArrayNode();
+ for (Command c : commands) {
+ commandsArray.add(commandToNode(c));
+ }
+ response.set("Commands", commandsArray);
+ return Response.ok(response).build();
+ }
+
+ private Response handleListCommandInvocations(JsonNode request, String region) {
+ String commandId = request.has("CommandId") ? request.path("CommandId").asText() : null;
+ String instanceId = request.has("InstanceId") ? request.path("InstanceId").asText() : null;
+ List<CommandInvocation> invocations = commandService.listCommandInvocations(commandId, instanceId, region);
+
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode invArray = objectMapper.createArrayNode();
+ for (CommandInvocation inv : invocations) {
+ invArray.add(invocationToNode(inv));
+ }
+ response.set("CommandInvocations", invArray);
+ return Response.ok(response).build();
+ }
+
+ private Response handleCancelCommand(JsonNode request, String region) {
+ String commandId = request.path("CommandId").asText();
+ List<String> instanceIds = new ArrayList<>();
+ request.path("InstanceIds").forEach(n -> instanceIds.add(n.asText()));
+ commandService.cancelCommand(commandId, instanceIds, region);
+ return Response.ok(objectMapper.createObjectNode()).build();
+ }
+
+ private Response handleDescribeInstanceInformation(JsonNode request, String region) {
+ List<InstanceInformation> instances = commandService.describeInstanceInformation(region);
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode list = objectMapper.createArrayNode();
+ for (InstanceInformation info : instances) {
+ list.add(instanceInfoToNode(info));
+ }
+ response.set("InstanceInformationList", list);
+ return Response.ok(response).build();
+ }
+
+ // ── Serialisation helpers ──────────────────────────────────────────────
+
+ private ObjectNode commandToNode(Command c) {
+ ObjectNode node = objectMapper.createObjectNode();
+ node.put("CommandId", c.getCommandId());
+ node.put("DocumentName", c.getDocumentName());
+ if (c.getDocumentVersion() != null) node.put("DocumentVersion", c.getDocumentVersion());
+ if (c.getComment() != null) node.put("Comment", c.getComment());
+ if (c.getRequestedDateTime() != null) node.put("RequestedDateTime", c.getRequestedDateTime().toEpochMilli() / 1000.0);
+ if (c.getExpiresAfter() != null) node.put("ExpiresAfter", c.getExpiresAfter().toEpochMilli() / 1000.0);
+ node.put("Status", c.getStatus());
+ node.put("StatusDetails", c.getStatusDetails());
+ node.put("TargetCount", c.getTargetCount());
+ node.put("CompletedCount", c.getCompletedCount());
+ node.put("ErrorCount", c.getErrorCount());
+ node.put("TimeoutSeconds", c.getTimeoutSeconds());
+ if (c.getInstanceIds() != null) {
+ ArrayNode ids = objectMapper.createArrayNode();
+ c.getInstanceIds().forEach(ids::add);
+ node.set("InstanceIds", ids);
+ }
+ if (c.getParameters() != null) {
+ ObjectNode params = objectMapper.createObjectNode();
+ c.getParameters().forEach((k, v) -> {
+ ArrayNode arr = objectMapper.createArrayNode();
+ v.forEach(arr::add);
+ params.set(k, arr);
+ });
+ node.set("Parameters", params);
+ }
+ return node;
+ }
+
+ private ObjectNode invocationToNode(CommandInvocation inv) {
+ ObjectNode node = objectMapper.createObjectNode();
+ node.put("CommandId", inv.getCommandId());
+ node.put("InstanceId", inv.getInstanceId());
+ if (inv.getComment() != null) node.put("Comment", inv.getComment());
+ node.put("DocumentName", inv.getDocumentName());
+ if (inv.getDocumentVersion() != null) node.put("DocumentVersion", inv.getDocumentVersion());
+ if (inv.getRequestedDateTime() != null) node.put("RequestedDateTime", inv.getRequestedDateTime().toEpochMilli() / 1000.0);
+ node.put("Status", inv.getStatus());
+ node.put("StatusDetails", inv.getStatusDetails());
+ return node;
+ }
+
+ private ObjectNode invocationToDetailNode(CommandInvocation inv) {
+ ObjectNode node = invocationToNode(inv);
+ node.put("StandardOutputContent", inv.getStandardOutputContent() != null ? inv.getStandardOutputContent() : "");
+ node.put("StandardErrorContent", inv.getStandardErrorContent() != null ? inv.getStandardErrorContent() : "");
+ node.put("ResponseCode", inv.getResponseCode());
+ if (inv.getExecutionStartDateTime() != null) {
+ node.put("ExecutionStartDateTime", inv.getExecutionStartDateTime().toString());
+ }
+ if (inv.getExecutionEndDateTime() != null) {
+ node.put("ExecutionEndDateTime", inv.getExecutionEndDateTime().toString());
+ }
+ return node;
+ }
+
+ private ObjectNode instanceInfoToNode(InstanceInformation info) {
+ ObjectNode node = objectMapper.createObjectNode();
+ node.put("InstanceId", info.getInstanceId());
+ node.put("PingStatus", info.getPingStatus());
+ node.put("AgentVersion", info.getAgentVersion());
+ if (info.getPlatformType() != null) node.put("PlatformType", info.getPlatformType());
+ if (info.getPlatformName() != null) node.put("PlatformName", info.getPlatformName());
+ if (info.getPlatformVersion() != null) node.put("PlatformVersion", info.getPlatformVersion());
+ if (info.getIpAddress() != null) node.put("IPAddress", info.getIpAddress());
+ if (info.getComputerName() != null) node.put("ComputerName", info.getComputerName());
+ node.put("ResourceType", info.getResourceType());
+ if (info.getLastPingDateTime() != null) node.put("LastPingDateTime", info.getLastPingDateTime().toEpochMilli() / 1000.0);
+ if (info.getRegistrationDate() != null) node.put("RegistrationDate", info.getRegistrationDate().toEpochMilli() / 1000.0);
+ return node;
+ }
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ssm/model/Command.java b/src/main/java/io/github/hectorvent/floci/services/ssm/model/Command.java
new file mode 100644
index 0000000000..d428f50648
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ssm/model/Command.java
@@ -0,0 +1,88 @@
+package io.github.hectorvent.floci.services.ssm.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.time.Instant;
+import java.util.List;
+import java.util.Map;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class Command {
+
+ private String commandId;
+ private String documentName;
+ private String documentVersion;
+ private String comment;
+ private Instant expiresAfter;
+ private Map<String, List<String>> parameters;
+ private List<String> instanceIds;
+ private Instant requestedDateTime;
+ private String status = "Pending";
+ private String statusDetails = "Pending";
+ private int timeoutSeconds = 3600;
+ private int targetCount;
+ private int completedCount;
+ private int errorCount;
+ private String outputS3BucketName;
+ private String outputS3KeyPrefix;
+ private String outputS3Region;
+ private String region;
+
+ public Command() {}
+
+ public String getCommandId() { return commandId; }
+ public void setCommandId(String commandId) { this.commandId = commandId; }
+
+ public String getDocumentName() { return documentName; }
+ public void setDocumentName(String documentName) { this.documentName = documentName; }
+
+ public String getDocumentVersion() { return documentVersion; }
+ public void setDocumentVersion(String documentVersion) { this.documentVersion = documentVersion; }
+
+ public String getComment() { return comment; }
+ public void setComment(String comment) { this.comment = comment; }
+
+ public Instant getExpiresAfter() { return expiresAfter; }
+ public void setExpiresAfter(Instant expiresAfter) { this.expiresAfter = expiresAfter; }
+
+ public Map<String, List<String>> getParameters() { return parameters; }
+ public void setParameters(Map<String, List<String>> parameters) { this.parameters = parameters; }
+
+ public List<String> getInstanceIds() { return instanceIds; }
+ public void setInstanceIds(List<String> instanceIds) { this.instanceIds = instanceIds; }
+
+ public Instant getRequestedDateTime() { return requestedDateTime; }
+ public void setRequestedDateTime(Instant requestedDateTime) { this.requestedDateTime = requestedDateTime; }
+
+ public String getStatus() { return status; }
+ public void setStatus(String status) { this.status = status; }
+
+ public String getStatusDetails() { return statusDetails; }
+ public void setStatusDetails(String statusDetails) { this.statusDetails = statusDetails; }
+
+ public int getTimeoutSeconds() { return timeoutSeconds; }
+ public void setTimeoutSeconds(int timeoutSeconds) { this.timeoutSeconds = timeoutSeconds; }
+
+ public int getTargetCount() { return targetCount; }
+ public void setTargetCount(int targetCount) { this.targetCount = targetCount; }
+
+ public int getCompletedCount() { return completedCount; }
+ public void setCompletedCount(int completedCount) { this.completedCount = completedCount; }
+
+ public int getErrorCount() { return errorCount; }
+ public void setErrorCount(int errorCount) { this.errorCount = errorCount; }
+
+ public String getOutputS3BucketName() { return outputS3BucketName; }
+ public void setOutputS3BucketName(String outputS3BucketName) { this.outputS3BucketName = outputS3BucketName; }
+
+ public String getOutputS3KeyPrefix() { return outputS3KeyPrefix; }
+ public void setOutputS3KeyPrefix(String outputS3KeyPrefix) { this.outputS3KeyPrefix = outputS3KeyPrefix; }
+
+ public String getOutputS3Region() { return outputS3Region; }
+ public void setOutputS3Region(String outputS3Region) { this.outputS3Region = outputS3Region; }
+
+ public String getRegion() { return region; }
+ public void setRegion(String region) { this.region = region; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ssm/model/CommandInvocation.java b/src/main/java/io/github/hectorvent/floci/services/ssm/model/CommandInvocation.java
new file mode 100644
index 0000000000..ea9999f4d3
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ssm/model/CommandInvocation.java
@@ -0,0 +1,70 @@
+package io.github.hectorvent.floci.services.ssm.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.time.Instant;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class CommandInvocation {
+
+ private String commandId;
+ private String instanceId;
+ private String comment;
+ private String documentName;
+ private String documentVersion;
+ private Instant requestedDateTime;
+ private String status = "Pending";
+ private String statusDetails = "Pending";
+ private String standardOutputContent = "";
+ private String standardErrorContent = "";
+ private int responseCode = -1;
+ private Instant executionStartDateTime;
+ private Instant executionEndDateTime;
+ private String region;
+
+ public CommandInvocation() {}
+
+ public String getCommandId() { return commandId; }
+ public void setCommandId(String commandId) { this.commandId = commandId; }
+
+ public String getInstanceId() { return instanceId; }
+ public void setInstanceId(String instanceId) { this.instanceId = instanceId; }
+
+ public String getComment() { return comment; }
+ public void setComment(String comment) { this.comment = comment; }
+
+ public String getDocumentName() { return documentName; }
+ public void setDocumentName(String documentName) { this.documentName = documentName; }
+
+ public String getDocumentVersion() { return documentVersion; }
+ public void setDocumentVersion(String documentVersion) { this.documentVersion = documentVersion; }
+
+ public Instant getRequestedDateTime() { return requestedDateTime; }
+ public void setRequestedDateTime(Instant requestedDateTime) { this.requestedDateTime = requestedDateTime; }
+
+ public String getStatus() { return status; }
+ public void setStatus(String status) { this.status = status; }
+
+ public String getStatusDetails() { return statusDetails; }
+ public void setStatusDetails(String statusDetails) { this.statusDetails = statusDetails; }
+
+ public String getStandardOutputContent() { return standardOutputContent; }
+ public void setStandardOutputContent(String standardOutputContent) { this.standardOutputContent = standardOutputContent; }
+
+ public String getStandardErrorContent() { return standardErrorContent; }
+ public void setStandardErrorContent(String standardErrorContent) { this.standardErrorContent = standardErrorContent; }
+
+ public int getResponseCode() { return responseCode; }
+ public void setResponseCode(int responseCode) { this.responseCode = responseCode; }
+
+ public Instant getExecutionStartDateTime() { return executionStartDateTime; }
+ public void setExecutionStartDateTime(Instant executionStartDateTime) { this.executionStartDateTime = executionStartDateTime; }
+
+ public Instant getExecutionEndDateTime() { return executionEndDateTime; }
+ public void setExecutionEndDateTime(Instant executionEndDateTime) { this.executionEndDateTime = executionEndDateTime; }
+
+ public String getRegion() { return region; }
+ public void setRegion(String region) { this.region = region; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ssm/model/InstanceInformation.java b/src/main/java/io/github/hectorvent/floci/services/ssm/model/InstanceInformation.java
new file mode 100644
index 0000000000..92e17e15fb
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ssm/model/InstanceInformation.java
@@ -0,0 +1,66 @@
+package io.github.hectorvent.floci.services.ssm.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.time.Instant;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class InstanceInformation {
+
+ private String instanceId;
+ private String agentName = "amazon-ssm-agent";
+ private String agentVersion = "3.2.2172.0";
+ private String pingStatus = "Online";
+ private Instant lastPingDateTime;
+ private String platformType;
+ private String platformName;
+ private String platformVersion;
+ private String ipAddress;
+ private String computerName;
+ private String resourceType = "EC2Instance";
+ private Instant registrationDate;
+ private String region;
+
+ public InstanceInformation() {}
+
+ public String getInstanceId() { return instanceId; }
+ public void setInstanceId(String instanceId) { this.instanceId = instanceId; }
+
+ public String getAgentName() { return agentName; }
+ public void setAgentName(String agentName) { this.agentName = agentName; }
+
+ public String getAgentVersion() { return agentVersion; }
+ public void setAgentVersion(String agentVersion) { this.agentVersion = agentVersion; }
+
+ public String getPingStatus() { return pingStatus; }
+ public void setPingStatus(String pingStatus) { this.pingStatus = pingStatus; }
+
+ public Instant getLastPingDateTime() { return lastPingDateTime; }
+ public void setLastPingDateTime(Instant lastPingDateTime) { this.lastPingDateTime = lastPingDateTime; }
+
+ public String getPlatformType() { return platformType; }
+ public void setPlatformType(String platformType) { this.platformType = platformType; }
+
+ public String getPlatformName() { return platformName; }
+ public void setPlatformName(String platformName) { this.platformName = platformName; }
+
+ public String getPlatformVersion() { return platformVersion; }
+ public void setPlatformVersion(String platformVersion) { this.platformVersion = platformVersion; }
+
+ public String getIpAddress() { return ipAddress; }
+ public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; }
+
+ public String getComputerName() { return computerName; }
+ public void setComputerName(String computerName) { this.computerName = computerName; }
+
+ public String getResourceType() { return resourceType; }
+ public void setResourceType(String resourceType) { this.resourceType = resourceType; }
+
+ public Instant getRegistrationDate() { return registrationDate; }
+ public void setRegistrationDate(Instant registrationDate) { this.registrationDate = registrationDate; }
+
+ public String getRegion() { return region; }
+ public void setRegion(String region) { this.region = region; }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ssm/SsmSendCommandIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ssm/SsmSendCommandIntegrationTest.java
new file mode 100644
index 0000000000..9363364fa9
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ssm/SsmSendCommandIntegrationTest.java
@@ -0,0 +1,382 @@
+package io.github.hectorvent.floci.services.ssm;
+
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+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 java.util.Base64;
+import java.util.UUID;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.*;
+
+@QuarkusTest
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class SsmSendCommandIntegrationTest {
+
+ private static final String SSM_CT = "application/x-amz-json-1.1";
+ private static final String INSTANCE_ID = "i-0abc1234def56789a";
+ private static String commandId;
+
+ @BeforeAll
+ static void setup() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ // ── Agent registration ─────────────────────────────────────────────────
+
+ @Test
+ @Order(1)
+ void agentRegistersViaUpdateInstanceInformation() {
+ given()
+ .header("X-Amz-Target", "AmazonSSM.UpdateInstanceInformation")
+ .contentType(SSM_CT)
+ .body("""
+ {
+ "InstanceId": "%s",
+ "AgentName": "amazon-ssm-agent",
+ "AgentVersion": "3.2.2172.0",
+ "PlatformType": "Linux",
+ "PlatformName": "Amazon Linux",
+ "PlatformVersion": "2023",
+ "IPAddress": "172.31.10.20",
+ "Hostname": "ip-172-31-10-20",
+ "AgentStatus": "Active"
+ }
+ """.formatted(INSTANCE_ID))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+
+ @Test
+ @Order(2)
+ void describeInstanceInformationShowsRegisteredAgent() {
+ given()
+ .header("X-Amz-Target", "AmazonSSM.DescribeInstanceInformation")
+ .contentType(SSM_CT)
+ .body("{}")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("InstanceInformationList", not(empty()))
+ .body("InstanceInformationList[0].InstanceId", equalTo(INSTANCE_ID))
+ .body("InstanceInformationList[0].PingStatus", equalTo("Online"))
+ .body("InstanceInformationList[0].PlatformType", equalTo("Linux"));
+ }
+
+ // ── SendCommand ────────────────────────────────────────────────────────
+
+ @Test
+ @Order(3)
+ void sendCommandCreatesCommandRecord() {
+ String response = given()
+ .header("X-Amz-Target", "AmazonSSM.SendCommand")
+ .contentType(SSM_CT)
+ .body("""
+ {
+ "InstanceIds": ["%s"],
+ "DocumentName": "AWS-RunShellScript",
+ "Parameters": {
+ "commands": ["echo hello"]
+ },
+ "Comment": "test run",
+ "TimeoutSeconds": 60
+ }
+ """.formatted(INSTANCE_ID))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("Command.CommandId", notNullValue())
+ .body("Command.DocumentName", equalTo("AWS-RunShellScript"))
+ .body("Command.Status", equalTo("InProgress"))
+ .body("Command.TargetCount", equalTo(1))
+ .extract().body().asString();
+
+ commandId = io.restassured.path.json.JsonPath.from(response).getString("Command.CommandId");
+ }
+
+ @Test
+ @Order(4)
+ void listCommandsReturnsCreatedCommand() {
+ given()
+ .header("X-Amz-Target", "AmazonSSM.ListCommands")
+ .contentType(SSM_CT)
+ .body("{}")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("Commands", not(empty()))
+ .body("Commands[0].DocumentName", equalTo("AWS-RunShellScript"));
+ }
+
+ @Test
+ @Order(5)
+ void listCommandInvocationsReturnsInvocation() {
+ given()
+ .header("X-Amz-Target", "AmazonSSM.ListCommandInvocations")
+ .contentType(SSM_CT)
+ .body("""
+ { "CommandId": "%s" }
+ """.formatted(commandId))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("CommandInvocations", hasSize(1))
+ .body("CommandInvocations[0].InstanceId", equalTo(INSTANCE_ID))
+ .body("CommandInvocations[0].Status", anyOf(equalTo("Pending"), equalTo("InProgress")));
+ }
+
+ // ── ec2messages agent protocol ─────────────────────────────────────────
+
+ @Test
+ @Order(6)
+ void agentGetsEndpoint() {
+ given()
+ .header("X-Amz-Target", "AmazonSSMMessageDeliveryService.GetEndpoint")
+ .contentType(SSM_CT)
+ .body("""
+ {
+ "Destination": "%s",
+ "Protocol": "ec2messages"
+ }
+ """.formatted(INSTANCE_ID))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("Endpoint.Protocol", equalTo("ec2messages"))
+ .body("Endpoint.Endpoint", notNullValue());
+ }
+
+ @Test
+ @Order(7)
+ void agentPollsAndGetsMessage() {
+ given()
+ .header("X-Amz-Target", "AmazonSSMMessageDeliveryService.GetMessages")
+ .contentType(SSM_CT)
+ .body("""
+ {
+ "Destination": "%s",
+ "MessagesRequestId": "%s",
+ "VisibilityTimeoutInSeconds": 30
+ }
+ """.formatted(INSTANCE_ID, UUID.randomUUID()))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("Messages", hasSize(1))
+ .body("Messages[0].MessageId", notNullValue())
+ .body("Messages[0].Topic", containsString("aws.ssm.sendCommand"))
+ .body("Messages[0].Payload", notNullValue());
+ }
+
+ @Test
+ @Order(8)
+ void agentAcknowledgesMessage() {
+ // First poll to get the message ID
+ String msgId = given()
+ .header("X-Amz-Target", "AmazonSSMMessageDeliveryService.GetMessages")
+ .contentType(SSM_CT)
+ .body("""
+ {
+ "Destination": "%s",
+ "MessagesRequestId": "%s",
+ "VisibilityTimeoutInSeconds": 30
+ }
+ """.formatted(INSTANCE_ID, UUID.randomUUID()))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().jsonPath().getString("Messages[0].MessageId");
+
+ // If no messages left (already polled in order 7), re-send another command
+ if (msgId == null) {
+ // Send another command and poll for it
+ String resp = given()
+ .header("X-Amz-Target", "AmazonSSM.SendCommand")
+ .contentType(SSM_CT)
+ .body("""
+ {
+ "InstanceIds": ["%s"],
+ "DocumentName": "AWS-RunShellScript",
+ "Parameters": { "commands": ["echo ack-test"] }
+ }
+ """.formatted(INSTANCE_ID))
+ .when().post("/")
+ .then().statusCode(200).extract().body().asString();
+
+ String newCmdId = io.restassured.path.json.JsonPath.from(resp).getString("Command.CommandId");
+
+ msgId = given()
+ .header("X-Amz-Target", "AmazonSSMMessageDeliveryService.GetMessages")
+ .contentType(SSM_CT)
+ .body("""
+ {
+ "Destination": "%s",
+ "MessagesRequestId": "%s",
+ "VisibilityTimeoutInSeconds": 30
+ }
+ """.formatted(INSTANCE_ID, UUID.randomUUID()))
+ .when().post("/")
+ .then().statusCode(200).extract().jsonPath().getString("Messages[0].MessageId");
+ }
+
+ // Acknowledge
+ given()
+ .header("X-Amz-Target", "AmazonSSMMessageDeliveryService.AcknowledgeMessage")
+ .contentType(SSM_CT)
+ .body("""
+ { "MessageId": "%s" }
+ """.formatted(msgId))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+
+ @Test
+ @Order(9)
+ void agentSendsReplyAndCommandStatusUpdates() {
+ // Send a fresh command
+ String resp = given()
+ .header("X-Amz-Target", "AmazonSSM.SendCommand")
+ .contentType(SSM_CT)
+ .body("""
+ {
+ "InstanceIds": ["%s"],
+ "DocumentName": "AWS-RunShellScript",
+ "Parameters": { "commands": ["echo world"] }
+ }
+ """.formatted(INSTANCE_ID))
+ .when().post("/")
+ .then().statusCode(200).extract().body().asString();
+
+ String cid = io.restassured.path.json.JsonPath.from(resp).getString("Command.CommandId");
+
+ // Poll
+ String msgId = given()
+ .header("X-Amz-Target", "AmazonSSMMessageDeliveryService.GetMessages")
+ .contentType(SSM_CT)
+ .body("""
+ {
+ "Destination": "%s",
+ "MessagesRequestId": "%s",
+ "VisibilityTimeoutInSeconds": 30
+ }
+ """.formatted(INSTANCE_ID, UUID.randomUUID()))
+ .when().post("/")
+ .then().statusCode(200).extract().jsonPath().getString("Messages[0].MessageId");
+
+ // Build a SendReply payload (base64 encoded agent output)
+ String replyPayload = buildReplyPayload("world\n", "Success", 0);
+
+ // Send reply
+ given()
+ .header("X-Amz-Target", "AmazonSSMMessageDeliveryService.SendReply")
+ .contentType(SSM_CT)
+ .body("""
+ {
+ "MessageId": "%s",
+ "Payload": "%s"
+ }
+ """.formatted(msgId, replyPayload))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ // Verify GetCommandInvocation reflects the result
+ given()
+ .header("X-Amz-Target", "AmazonSSM.GetCommandInvocation")
+ .contentType(SSM_CT)
+ .body("""
+ {
+ "CommandId": "%s",
+ "InstanceId": "%s"
+ }
+ """.formatted(cid, INSTANCE_ID))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("Status", equalTo("Success"))
+ .body("ResponseCode", equalTo(0))
+ .body("StandardOutputContent", containsString("world"));
+ }
+
+ @Test
+ @Order(10)
+ void cancelCommandUpdatesStatus() {
+ String resp = given()
+ .header("X-Amz-Target", "AmazonSSM.SendCommand")
+ .contentType(SSM_CT)
+ .body("""
+ {
+ "InstanceIds": ["%s"],
+ "DocumentName": "AWS-RunShellScript",
+ "Parameters": { "commands": ["sleep 100"] }
+ }
+ """.formatted(INSTANCE_ID))
+ .when().post("/")
+ .then().statusCode(200).extract().body().asString();
+
+ String cid = io.restassured.path.json.JsonPath.from(resp).getString("Command.CommandId");
+
+ given()
+ .header("X-Amz-Target", "AmazonSSM.CancelCommand")
+ .contentType(SSM_CT)
+ .body("""
+ { "CommandId": "%s" }
+ """.formatted(cid))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ given()
+ .header("X-Amz-Target", "AmazonSSM.ListCommands")
+ .contentType(SSM_CT)
+ .body("""
+ { "CommandId": "%s" }
+ """.formatted(cid))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("Commands[0].Status", equalTo("Cancelled"));
+ }
+
+ private static String buildReplyPayload(String stdout, String status, int returnCode) {
+ String json = """
+ {
+ "additionalInfo": {
+ "agent": { "name": "amazon-ssm-agent", "version": "3.2.2172.0" }
+ },
+ "documentTraceOutput": "",
+ "runtimeStatus": {
+ "runShellScript": {
+ "status": "%s",
+ "returnCode": %d,
+ "standardOutput": "%s",
+ "standardError": "",
+ "startDateTime": "2026-01-01T00:00:00Z",
+ "endDateTime": "2026-01-01T00:00:01Z"
+ }
+ }
+ }
+ """.formatted(status, returnCode, stdout.replace("\n", "\\n").replace("\"", "\\\""));
+ return Base64.getEncoder().encodeToString(json.getBytes());
+ }
+}