Light, fluffy, and always free - The AWS Local Emulator alternative
feat(ssm): model documents and associations with full lifecycle operations (#3057)
Vũ Thế Huyf00fb4c289ad
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.javaindex 3c48d3ca65..d07e519d78 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@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.services.ssm.model.Parameter;import io.github.hectorvent.floci.services.ssm.model.ParameterHistory;import io.github.hectorvent.floci.services.ssm.model.PatchBaselineIdentity;import io.github.hectorvent.floci.services.ssm.model.ServiceSetting;+import io.github.hectorvent.floci.services.ssm.model.SsmAssociation;import io.github.hectorvent.floci.services.ssm.model.SsmDocument;import com.fasterxml.jackson.annotation.JsonProperty;import com.fasterxml.jackson.databind.JsonNode;@@ -23,6 +24,7 @@ import jakarta.ws.rs.core.Response;import java.util.ArrayList;import java.util.HashMap;import java.util.HashSet;+import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Set;@@ -80,9 +82,14 @@ public class SsmJsonHandler {// Document share permissionscase "ModifyDocumentPermission" -> handleModifyDocumentPermission(request, region);case "DescribeDocumentPermission" -> handleDescribeDocumentPermission(request, region);- // Read-only list operations (resources not modeled: empty results)case "ListDocuments" -> handleListDocuments(request, region);+ // Associations+ case "CreateAssociation" -> handleCreateAssociation(request, region);+ case "UpdateAssociation" -> handleUpdateAssociation(request, region);+ case "DescribeAssociation" -> handleDescribeAssociation(request, region);+ case "DeleteAssociation" -> handleDeleteAssociation(request, region);case "ListAssociations" -> handleListAssociations(request, region);+ // Read-only list operations (resources not modeled: empty results)case "DescribeMaintenanceWindows" -> handleDescribeMaintenanceWindows(request, region);// Agent registration (internal, not in public SDK)case "UpdateInstanceInformation" -> handleUpdateInstanceInformation(request, region);@@ -418,11 +425,25 @@ public class SsmJsonHandler {String name = requireDocumentNameOrArn(request);SsmDocument document = ssmService.getDocument(name, region);+ String requestedVersion = request.hasNonNull("DocumentVersion") ? request.path("DocumentVersion").asText() : null;+ String effectiveVersion = String.valueOf(document.getDocumentVersion());+ String effectiveContent = document.getContent();++ if (requestedVersion != null && !requestedVersion.isBlank()+ && !"$LATEST".equals(requestedVersion) && !"$DEFAULT".equals(requestedVersion)) {+ if (!document.hasRetainedContent(requestedVersion)) {+ throw new AwsException("InvalidDocumentVersion",+ "The document version is not valid or does not exist.", 400);+ }+ effectiveVersion = requestedVersion;+ effectiveContent = document.getContentForVersion(requestedVersion);+ }+ObjectNode response = objectMapper.createObjectNode();response.put("Name", document.getName());response.put("DocumentType", document.getDocumentType());- response.put("DocumentVersion", String.valueOf(document.getDocumentVersion()));- response.put("Content", document.getContent());+ response.put("DocumentVersion", effectiveVersion);+ response.put("Content", effectiveContent);response.put("Status", document.getStatus());return Response.ok(response).build();}@@ -514,19 +535,357 @@ public class SsmJsonHandler {}private Response handleListDocuments(JsonNode request, String region) {- // SSM documents are not modeled: return an empty list.+ Map<String, List<String>> filters = new HashMap<>();+ if (request.has("Filters") && request.path("Filters").isArray()) {+ for (JsonNode f : request.path("Filters")) {+ String key = f.path("Key").asText("");+ List<String> values = new ArrayList<>();+ if (f.has("Values") && f.path("Values").isArray()) {+ f.path("Values").forEach(v -> values.add(v.asText()));+ } else if (f.has("Value")) {+ values.add(f.path("Value").asText());+ }+ if (!key.isEmpty() && !values.isEmpty()) {+ filters.computeIfAbsent(key, k -> new ArrayList<>()).addAll(values);+ }+ }+ }+ if (request.has("DocumentFilterList") && request.path("DocumentFilterList").isArray()) {+ for (JsonNode f : request.path("DocumentFilterList")) {+ String key = f.has("key") ? f.path("key").asText("") : f.path("Key").asText("");+ List<String> values = new ArrayList<>();+ if (f.has("Values") && f.path("Values").isArray()) {+ f.path("Values").forEach(v -> values.add(v.asText()));+ } else if (f.has("value")) {+ values.add(f.path("value").asText());+ } else if (f.has("Value")) {+ values.add(f.path("Value").asText());+ }+ if (!key.isEmpty() && !values.isEmpty()) {+ filters.computeIfAbsent(key, k -> new ArrayList<>()).addAll(values);+ }+ }+ }++ List<SsmDocument> documents = ssmService.listDocuments(region, filters.isEmpty() ? null : filters);+ObjectNode response = objectMapper.createObjectNode();- response.set("DocumentIdentifiers", objectMapper.createArrayNode());+ ArrayNode docArray = objectMapper.createArrayNode();+ for (SsmDocument d : documents) {+ ObjectNode docNode = objectMapper.createObjectNode();+ docNode.put("Name", d.getName());+ if (d.getCreatedDate() != null) {+ docNode.put("CreatedDate", d.getCreatedDate().toEpochMilli() / 1000.0);+ }+ docNode.put("DocumentType", d.getDocumentType());+ docNode.put("DocumentVersion", String.valueOf(d.getDocumentVersion()));+ if (d.getOwner() != null) {+ docNode.put("Owner", d.getOwner());+ }+ if (d.getPlatformTypes() != null) {+ ArrayNode platforms = objectMapper.createArrayNode();+ d.getPlatformTypes().forEach(platforms::add);+ docNode.set("PlatformTypes", platforms);+ }+ if (d.getSchemaVersion() != null) {+ docNode.put("SchemaVersion", d.getSchemaVersion());+ }+ if (d.getDocumentFormat() != null) {+ docNode.put("DocumentFormat", d.getDocumentFormat());+ }+ docArray.add(docNode);+ }+ response.set("DocumentIdentifiers", docArray);return Response.ok(response).build();}+ private List<SsmAssociation.Target> parseTargets(JsonNode request) {+ if (!request.hasNonNull("Targets") || !request.path("Targets").isArray()) {+ return null;+ }+ List<SsmAssociation.Target> targets = new ArrayList<>();+ for (JsonNode t : request.path("Targets")) {+ String key = t.path("Key").asText();+ List<String> values = new ArrayList<>();+ if (t.has("Values") && t.path("Values").isArray()) {+ t.path("Values").forEach(v -> values.add(v.asText()));+ }+ targets.add(new SsmAssociation.Target(key, values));+ }+ return targets;+ }++ private Map<String, List<String>> parseParameters(JsonNode request) {+ if (!request.hasNonNull("Parameters") || !request.path("Parameters").isObject()) {+ return null;+ }+ Map<String, List<String>> parameters = new HashMap<>();+ Iterator<Map.Entry<String, JsonNode>> fields = request.path("Parameters").fields();+ while (fields.hasNext()) {+ Map.Entry<String, JsonNode> entry = fields.next();+ List<String> values = new ArrayList<>();+ if (entry.getValue().isArray()) {+ entry.getValue().forEach(v -> values.add(v.asText()));+ } else if (entry.getValue().isTextual()) {+ values.add(entry.getValue().asText());+ }+ parameters.put(entry.getKey(), values);+ }+ return parameters;+ }++ private Response handleCreateAssociation(JsonNode request, String region) {+ JsonNode nameNode = request.path("Name");+ if (!nameNode.isTextual() || nameNode.asText().isBlank()) {+ throw new AwsException("ValidationException",+ "1 validation error detected: Value null at 'name' failed to satisfy constraint: Member must not be null",+ 400);+ }+ String name = nameNode.asText();++ String associationName = request.hasNonNull("AssociationName") ? request.path("AssociationName").asText() : null;+ String documentVersion = request.hasNonNull("DocumentVersion") ? request.path("DocumentVersion").asText() : null;+ String instanceId = request.hasNonNull("InstanceId") ? request.path("InstanceId").asText() : null;+ String scheduleExpression = request.hasNonNull("ScheduleExpression") ? request.path("ScheduleExpression").asText() : null;+ String maxErrors = request.hasNonNull("MaxErrors") ? request.path("MaxErrors").asText() : null;+ String maxConcurrency = request.hasNonNull("MaxConcurrency") ? request.path("MaxConcurrency").asText() : null;+ String complianceSeverity = request.hasNonNull("ComplianceSeverity") ? request.path("ComplianceSeverity").asText() : null;++ List<SsmAssociation.Target> targets = parseTargets(request);+ Map<String, List<String>> parameters = parseParameters(request);++ boolean hasInstanceId = instanceId != null && !instanceId.isBlank();+ boolean hasTargets = targets != null && !targets.isEmpty();+ if (!hasInstanceId && !hasTargets) {+ throw new AwsException("ValidationException",+ "Either InstanceId or Targets must be specified.", 400);+ }++ SsmAssociation assoc = ssmService.createAssociation(+ name, associationName, documentVersion, instanceId, targets, parameters, scheduleExpression,+ maxErrors, maxConcurrency, complianceSeverity, region);++ return Response.ok(associationDescriptionResponse(assoc)).build();+ }++ private Response handleUpdateAssociation(JsonNode request, String region) {+ String associationId = request.hasNonNull("AssociationId") ? request.path("AssociationId").asText() : null;+ if (associationId == null || associationId.isBlank()) {+ throw new AwsException("ValidationException",+ "1 validation error detected: Value null at 'associationId' failed to satisfy constraint: Member must not be null",+ 400);+ }++ String associationName = request.hasNonNull("AssociationName") ? request.path("AssociationName").asText() : null;+ String documentVersion = request.hasNonNull("DocumentVersion") ? request.path("DocumentVersion").asText() : null;+ String scheduleExpression = request.hasNonNull("ScheduleExpression") ? request.path("ScheduleExpression").asText() : null;+ String maxErrors = request.hasNonNull("MaxErrors") ? request.path("MaxErrors").asText() : null;+ String maxConcurrency = request.hasNonNull("MaxConcurrency") ? request.path("MaxConcurrency").asText() : null;+ String complianceSeverity = request.hasNonNull("ComplianceSeverity") ? request.path("ComplianceSeverity").asText() : null;+ List<SsmAssociation.Target> targets = parseTargets(request);+ Map<String, List<String>> parameters = parseParameters(request);++ SsmAssociation assoc = ssmService.updateAssociation(+ associationId, associationName, documentVersion, targets, parameters, scheduleExpression,+ maxErrors, maxConcurrency, complianceSeverity, region);++ return Response.ok(associationDescriptionResponse(assoc)).build();+ }+private Response handleListAssociations(JsonNode request, String region) {- // SSM associations are not modeled: return an empty list.+ Map<String, List<String>> filters = new HashMap<>();+ if (request.has("AssociationFilterList") && request.path("AssociationFilterList").isArray()) {+ for (JsonNode f : request.path("AssociationFilterList")) {+ String key = f.has("key") ? f.path("key").asText("") : f.path("Key").asText("");+ List<String> values = new ArrayList<>();+ if (f.has("value")) {+ values.add(f.path("value").asText());+ } else if (f.has("Value")) {+ values.add(f.path("Value").asText());+ } else if (f.has("Values") && f.path("Values").isArray()) {+ f.path("Values").forEach(v -> values.add(v.asText()));+ }+ if (!key.isEmpty() && !values.isEmpty()) {+ filters.computeIfAbsent(key, k -> new ArrayList<>()).addAll(values);+ }+ }+ }++ List<SsmAssociation> associations = ssmService.listAssociations(region, filters);+ObjectNode response = objectMapper.createObjectNode();- response.set("Associations", objectMapper.createArrayNode());+ ArrayNode associationsArray = objectMapper.createArrayNode();+ for (SsmAssociation assoc : associations) {+ associationsArray.add(associationSummaryToNode(assoc));+ }+ response.set("Associations", associationsArray);return Response.ok(response).build();}+ private Response handleDescribeAssociation(JsonNode request, String region) {+ String associationId = request.hasNonNull("AssociationId") ? request.path("AssociationId").asText() : null;+ String name = request.hasNonNull("Name") ? request.path("Name").asText() : null;+ String instanceId = request.hasNonNull("InstanceId") ? request.path("InstanceId").asText() : null;++ boolean hasAssocId = associationId != null && !associationId.isBlank();+ boolean hasNameAndInstance = (name != null && !name.isBlank()) && (instanceId != null && !instanceId.isBlank());+ if (!hasAssocId && !hasNameAndInstance) {+ throw new AwsException("ValidationException",+ "Either AssociationId or both Name and InstanceId must be specified.", 400);+ }++ SsmAssociation assoc = ssmService.describeAssociation(associationId, name, instanceId, region);+ return Response.ok(associationDescriptionResponse(assoc)).build();+ }++ private Response handleDeleteAssociation(JsonNode request, String region) {+ String associationId = request.hasNonNull("AssociationId") ? request.path("AssociationId").asText() : null;+ String name = request.hasNonNull("Name") ? request.path("Name").asText() : null;+ String instanceId = request.hasNonNull("InstanceId") ? request.path("InstanceId").asText() : null;++ boolean hasAssocId = associationId != null && !associationId.isBlank();+ boolean hasNameAndInstance = (name != null && !name.isBlank()) && (instanceId != null && !instanceId.isBlank());+ if (!hasAssocId && !hasNameAndInstance) {+ throw new AwsException("ValidationException",+ "Either AssociationId or both Name and InstanceId must be specified.", 400);+ }++ ssmService.deleteAssociation(associationId, name, instanceId, region);+ return Response.ok(objectMapper.createObjectNode()).build();+ }++ private ArrayNode targetsToArray(List<SsmAssociation.Target> targets) {+ ArrayNode targetsArray = objectMapper.createArrayNode();+ for (SsmAssociation.Target t : targets) {+ ObjectNode targetNode = objectMapper.createObjectNode();+ targetNode.put("Key", t.getKey());+ ArrayNode valuesArray = objectMapper.createArrayNode();+ if (t.getValues() != null) {+ t.getValues().forEach(valuesArray::add);+ }+ targetNode.set("Values", valuesArray);+ targetsArray.add(targetNode);+ }+ return targetsArray;+ }++ private ObjectNode associationSummaryToNode(SsmAssociation assoc) {+ ObjectNode node = objectMapper.createObjectNode();+ if (assoc.getAssociationId() != null) {+ node.put("AssociationId", assoc.getAssociationId());+ }+ if (assoc.getName() != null) {+ node.put("Name", assoc.getName());+ }+ if (assoc.getAssociationName() != null) {+ node.put("AssociationName", assoc.getAssociationName());+ }+ if (assoc.getAssociationVersion() != null) {+ node.put("AssociationVersion", assoc.getAssociationVersion());+ }+ if (assoc.getDocumentVersion() != null) {+ node.put("DocumentVersion", assoc.getDocumentVersion());+ }+ if (assoc.getInstanceId() != null) {+ node.put("InstanceId", assoc.getInstanceId());+ }+ if (assoc.getTargets() != null) {+ node.set("Targets", targetsToArray(assoc.getTargets()));+ }+ if (assoc.getOverview() != null) {+ ObjectNode overviewNode = objectMapper.createObjectNode();+ overviewNode.put("Status", assoc.getOverview().getStatus());+ overviewNode.put("DetailedStatus", assoc.getOverview().getDetailedStatus());+ node.set("Overview", overviewNode);+ }+ if (assoc.getScheduleExpression() != null) {+ node.put("ScheduleExpression", assoc.getScheduleExpression());+ }+ if (assoc.getLastExecutionDate() != null) {+ node.put("LastExecutionDate", assoc.getLastExecutionDate().toEpochMilli() / 1000.0);+ }+ return node;+ }++ private ObjectNode associationDescriptionResponse(SsmAssociation assoc) {+ ObjectNode response = objectMapper.createObjectNode();+ ObjectNode desc = objectMapper.createObjectNode();++ if (assoc.getAssociationId() != null) {+ desc.put("AssociationId", assoc.getAssociationId());+ }+ if (assoc.getName() != null) {+ desc.put("Name", assoc.getName());+ }+ if (assoc.getAssociationName() != null) {+ desc.put("AssociationName", assoc.getAssociationName());+ }+ if (assoc.getDocumentVersion() != null) {+ desc.put("DocumentVersion", assoc.getDocumentVersion());+ }+ if (assoc.getInstanceId() != null) {+ desc.put("InstanceId", assoc.getInstanceId());+ }+ if (assoc.getAssociationVersion() != null) {+ desc.put("AssociationVersion", assoc.getAssociationVersion());+ }+ if (assoc.getTargets() != null) {+ desc.set("Targets", targetsToArray(assoc.getTargets()));+ }+ if (assoc.getParameters() != null) {+ ObjectNode paramsNode = objectMapper.createObjectNode();+ for (Map.Entry<String, List<String>> entry : assoc.getParameters().entrySet()) {+ ArrayNode valuesArray = objectMapper.createArrayNode();+ if (entry.getValue() != null) {+ entry.getValue().forEach(valuesArray::add);+ }+ paramsNode.set(entry.getKey(), valuesArray);+ }+ desc.set("Parameters", paramsNode);+ }+ if (assoc.getScheduleExpression() != null) {+ desc.put("ScheduleExpression", assoc.getScheduleExpression());+ }+ if (assoc.getStatus() != null) {+ ObjectNode statusNode = objectMapper.createObjectNode();+ statusNode.put("Name", assoc.getStatus().getName());+ if (assoc.getStatus().getMessage() != null) {+ statusNode.put("Message", assoc.getStatus().getMessage());+ }+ if (assoc.getStatus().getDate() != null) {+ statusNode.put("Date", assoc.getStatus().getDate().toEpochMilli() / 1000.0);+ }+ if (assoc.getStatus().getAdditionalInfo() != null) {+ statusNode.put("AdditionalInfo", assoc.getStatus().getAdditionalInfo());+ }+ desc.set("Status", statusNode);+ }+ if (assoc.getOverview() != null) {+ ObjectNode overviewNode = objectMapper.createObjectNode();+ overviewNode.put("Status", assoc.getOverview().getStatus());+ overviewNode.put("DetailedStatus", assoc.getOverview().getDetailedStatus());+ desc.set("Overview", overviewNode);+ }+ if (assoc.getCreatedDate() != null) {+ desc.put("Date", assoc.getCreatedDate().toEpochMilli() / 1000.0);+ }+ if (assoc.getLastExecutionDate() != null) {+ desc.put("LastExecutionDate", assoc.getLastExecutionDate().toEpochMilli() / 1000.0);+ }+ if (assoc.getComplianceSeverity() != null) {+ desc.put("ComplianceSeverity", assoc.getComplianceSeverity());+ }+ if (assoc.getMaxConcurrency() != null) {+ desc.put("MaxConcurrency", assoc.getMaxConcurrency());+ }+ if (assoc.getMaxErrors() != null) {+ desc.put("MaxErrors", assoc.getMaxErrors());+ }++ response.set("AssociationDescription", desc);+ return response;+ }+private Response handleDescribeMaintenanceWindows(JsonNode request, String region) {// Maintenance windows are not modeled: return an empty list.ObjectNode response = objectMapper.createObjectNode();@@ -839,12 +1198,26 @@ public class SsmJsonHandler {String name = requireDocumentNameOrArn(request);SsmDocument document = ssmService.getDocument(name, region);+ String requestedVersion = request.hasNonNull("DocumentVersion") ? request.path("DocumentVersion").asText() : null;+ String effectiveVersion = String.valueOf(document.getDocumentVersion());+ String effectiveContent = document.getContent();++ if (requestedVersion != null && !requestedVersion.isBlank()+ && !"$LATEST".equals(requestedVersion) && !"$DEFAULT".equals(requestedVersion)) {+ if (!document.hasRetainedContent(requestedVersion)) {+ throw new AwsException("InvalidDocumentVersion",+ "The document version is not valid or does not exist.", 400);+ }+ effectiveVersion = requestedVersion;+ effectiveContent = document.getContentForVersion(requestedVersion);+ }+ObjectNode response = objectMapper.createObjectNode();ObjectNode documentNode = objectMapper.createObjectNode();documentNode.put("Name", document.getName());documentNode.put("DocumentType", document.getDocumentType());- documentNode.put("DocumentVersion", String.valueOf(document.getDocumentVersion()));- documentNode.put("Content", document.getContent());+ documentNode.put("DocumentVersion", effectiveVersion);+ documentNode.put("Content", effectiveContent);documentNode.put("Status", document.getStatus());if (document.getCreatedDate() != null) {documentNode.put("CreatedDate", document.getCreatedDate().toString());diff --git a/src/main/java/io/github/hectorvent/floci/services/ssm/SsmService.java b/src/main/java/io/github/hectorvent/floci/services/ssm/SsmService.javaindex a71b1cf2b7..c6195fffca 100644--- a/src/main/java/io/github/hectorvent/floci/services/ssm/SsmService.java+++ b/src/main/java/io/github/hectorvent/floci/services/ssm/SsmService.java@@ -10,6 +10,7 @@ import io.github.hectorvent.floci.services.ssm.model.Parameter;import io.github.hectorvent.floci.services.ssm.model.ParameterHistory;import io.github.hectorvent.floci.services.ssm.model.PatchBaselineIdentity;import io.github.hectorvent.floci.services.ssm.model.ServiceSetting;+import io.github.hectorvent.floci.services.ssm.model.SsmAssociation;import io.github.hectorvent.floci.services.ssm.model.SsmDocument;import com.fasterxml.jackson.core.type.TypeReference;import jakarta.enterprise.context.ApplicationScoped;@@ -46,6 +47,7 @@ public class SsmService implements ResourceProvider {private final StorageBackend<String, List<String>> documentPermissionStore;private final StorageBackend<String, SsmDocument> documentStore;private final StorageBackend<String, ServiceSetting> serviceSettingStore;+ private final StorageBackend<String, SsmAssociation> associationStore;private final int maxParameterHistory;private final RegionResolver regionResolver;@@ -67,6 +69,9 @@ public class SsmService implements ResourceProvider {storageFactory.create("ssm", "ssm-service-settings.json",new TypeReference<>() {}),+ storageFactory.create("ssm", "ssm-associations.json",+ new TypeReference<>() {+ }),config.services().ssm().maxParameterHistory(),regionResolver);@@ -80,7 +85,7 @@ public class SsmService implements ResourceProvider {StorageBackend<String, List<String>> documentPermissionStore,int maxParameterHistory) {this(parameterStore, historyStore, documentPermissionStore, new InMemoryStorage<>(),- new InMemoryStorage<>(), maxParameterHistory,+ new InMemoryStorage<>(), new InMemoryStorage<>(), maxParameterHistory,new RegionResolver("us-east-1", "000000000000"));}@@ -91,7 +96,7 @@ public class SsmService implements ResourceProvider {StorageBackend<String, List<ParameterHistory>> historyStore,int maxParameterHistory) {this(parameterStore, historyStore, new InMemoryStorage<>(), new InMemoryStorage<>(),- new InMemoryStorage<>(), maxParameterHistory,+ new InMemoryStorage<>(), new InMemoryStorage<>(), maxParameterHistory,new RegionResolver("us-east-1", "000000000000"));}@@ -101,11 +106,23 @@ public class SsmService implements ResourceProvider {StorageBackend<String, SsmDocument> documentStore,StorageBackend<String, ServiceSetting> serviceSettingStore,int maxParameterHistory, RegionResolver regionResolver) {+ this(parameterStore, historyStore, documentPermissionStore, documentStore,+ serviceSettingStore, new InMemoryStorage<>(), maxParameterHistory, regionResolver);+ }++ SsmService(StorageBackend<String, Parameter> parameterStore,+ StorageBackend<String, List<ParameterHistory>> historyStore,+ StorageBackend<String, List<String>> documentPermissionStore,+ StorageBackend<String, SsmDocument> documentStore,+ StorageBackend<String, ServiceSetting> serviceSettingStore,+ StorageBackend<String, SsmAssociation> associationStore,+ int maxParameterHistory, RegionResolver regionResolver) {this.parameterStore = parameterStore;this.historyStore = historyStore;this.documentPermissionStore = documentPermissionStore;this.documentStore = documentStore;this.serviceSettingStore = serviceSettingStore;+ this.associationStore = associationStore;this.maxParameterHistory = maxParameterHistory;this.regionResolver = regionResolver;}@@ -299,13 +316,16 @@ public class SsmService implements ResourceProvider {// can round-trip ModifyDocumentPermission -> DescribeDocumentPermission.// Both permission operations resolve the document first, so an unknown document// raises InvalidDocument instead of silently minting or reporting share state for- // a document that does not exist. (ListDocuments still returns an empty list; it- // is not wired to documentStore.)+ // a document that does not exist.public SsmDocument getDocument(String name, String region) {- return documentStore.get(regionKey(region, name))+ SsmDocument document = documentStore.get(regionKey(region, name)).orElseThrow(() -> new AwsException("InvalidDocument","Document " + name + " does not exist.", 400));+ if (document.getOwner() == null) {+ document.setOwner(regionResolver.getAccountId());+ }+ return document;}public synchronized SsmDocument createDocument(String name, String content, String documentType, String region) {@@ -315,6 +335,7 @@ public class SsmService implements ResourceProvider {"Document " + name + " already exists.", 400);}SsmDocument document = new SsmDocument(name, content, documentType);+ document.setOwner(regionResolver.getAccountId());documentStore.put(storageKey, document);return document;}@@ -329,8 +350,10 @@ public class SsmService implements ResourceProvider {"The content of the association document matches another document. "+ "Change the content of the document and try again.", 400);}+ long newVersion = document.getDocumentVersion() + 1;document.setContent(content);- document.setDocumentVersion(document.getDocumentVersion() + 1);+ document.setDocumentVersion(newVersion);+ document.getVersions().put(String.valueOf(newVersion), content);documentStore.put(storageKey, document);return document;}@@ -375,6 +398,262 @@ public class SsmService implements ResourceProvider {LOG.debugv("Modified document permission for {0}: {1} account(s) shared", name, accountIds.size());}+ public List<SsmDocument> listDocuments(String region, Map<String, List<String>> filters) {+ String prefix = regionKey(region, "");+ List<SsmDocument> docs = documentStore.scan(k -> k.startsWith(prefix));+ String accountId = regionResolver.getAccountId();+ for (SsmDocument d : docs) {+ if (d.getOwner() == null) {+ d.setOwner(accountId);+ }+ }+ if (filters == null || filters.isEmpty()) {+ return docs;+ }++ List<String> nameFilters = findFilterValues(filters, "Name");+ List<String> typeFilters = findFilterValues(filters, "DocumentType");+ List<String> ownerFilters = findFilterValues(filters, "Owner");+ List<String> platformFilters = findFilterValues(filters, "PlatformTypes");++ return docs.stream()+ .filter(d -> nameFilters.isEmpty()+ || nameFilters.contains(d.getName())+ || nameFilters.stream().anyMatch(n -> !n.isEmpty() && d.getName() != null && d.getName().startsWith(n)))+ .filter(d -> typeFilters.isEmpty()+ || typeFilters.stream().anyMatch(t -> t.equalsIgnoreCase(d.getDocumentType())))+ .filter(d -> ownerFilters.isEmpty()+ || ownerFilters.stream().anyMatch(o -> matchesOwner(o, d.getOwner(), accountId)))+ .filter(d -> platformFilters.isEmpty()+ || (d.getPlatformTypes() != null && platformFilters.stream()+ .anyMatch(p -> d.getPlatformTypes().stream().anyMatch(p::equalsIgnoreCase))))+ .toList();+ }++ /**+ * Every document visible through {@code documentStore} already belongs to the caller's+ * account (it is an account-partitioned store), so "Self"/"Private"/"All" and the caller's own+ * account id all match every visible document; "Amazon"/"Public"/"ThirdParty" match none, since+ * no AWS-owned or other-account documents are ever visible here. Documents created before the+ * {@code Owner} field existed persist with a null owner; since the store already guarantees the+ * caller's own partition, such a document is normalized to the current caller's account ID so+ * that it both matches owner filters and serializes its effective owner in list responses.+ */+ private boolean matchesOwner(String filterValue, String documentOwner, String accountId) {+ if ("Self".equalsIgnoreCase(filterValue) || "Private".equalsIgnoreCase(filterValue)+ || "All".equalsIgnoreCase(filterValue)) {+ return true;+ }+ if ("Amazon".equalsIgnoreCase(filterValue) || "Public".equalsIgnoreCase(filterValue)+ || "ThirdParty".equalsIgnoreCase(filterValue)) {+ return false;+ }+ String effectiveOwner = documentOwner != null ? documentOwner : accountId;+ return filterValue.equals(effectiveOwner);+ }++ private List<String> findFilterValues(Map<String, List<String>> filters, String targetKey) {+ if (filters == null) {+ return List.of();+ }+ for (Map.Entry<String, List<String>> entry : filters.entrySet()) {+ if (entry.getKey().equalsIgnoreCase(targetKey) && entry.getValue() != null) {+ return entry.getValue();+ }+ }+ return List.of();+ }++ /**+ * Rejects a {@code DocumentVersion} that cannot resolve on the target document.+ * Stored document versions are retained across updates, so numeric versions are accepted+ * when they exist in the document's version history; {@code $LATEST}/{@code $DEFAULT}+ * always resolve to the current version. {@link SsmDocument#hasVersion} also accepts a+ * numeric version that predates the retained history (see its javadoc) rather than rejecting+ * a version that legitimately existed just because its content was never captured.+ * Non-existent versions or malformed inputs throw {@code InvalidDocumentVersion}, matching+ * AWS SSM behavior.+ */+ private void validateDocumentVersion(SsmDocument document, String documentVersion) {+ if (documentVersion == null || documentVersion.isBlank()+ || "$LATEST".equals(documentVersion) || "$DEFAULT".equals(documentVersion)) {+ return;+ }+ if (!document.hasVersion(documentVersion)) {+ throw new AwsException("InvalidDocumentVersion",+ "The document version is not valid or does not exist.", 400);+ }+ }++ // ──────────────────────── Associations ───────────────────────────────────++ public synchronized SsmAssociation createAssociation(+ String name,+ String associationName,+ String documentVersion,+ String instanceId,+ List<SsmAssociation.Target> targets,+ Map<String, List<String>> parameters,+ String scheduleExpression,+ String region) {+ return createAssociation(name, associationName, documentVersion, instanceId, targets, parameters,+ scheduleExpression, null, null, null, region);+ }++ public synchronized SsmAssociation createAssociation(+ String name,+ String associationName,+ String documentVersion,+ String instanceId,+ List<SsmAssociation.Target> targets,+ Map<String, List<String>> parameters,+ String scheduleExpression,+ String maxErrors,+ String maxConcurrency,+ String complianceSeverity,+ String region) {+ SsmDocument document = getDocument(name, region);+ validateDocumentVersion(document, documentVersion);++ if (instanceId != null && !instanceId.isBlank()) {+ boolean duplicate = listAssociations(region).stream()+ .anyMatch(a -> Objects.equals(a.getName(), name) && Objects.equals(a.getInstanceId(), instanceId));+ if (duplicate) {+ throw new AwsException("AssociationAlreadyExists",+ "An association already exists for instance " + instanceId + " and document " + name + ".", 400);+ }+ } else if (targets != null && !targets.isEmpty()) {+ boolean duplicate = listAssociations(region).stream()+ .anyMatch(a -> Objects.equals(a.getName(), name) && Objects.equals(a.getTargets(), targets));+ if (duplicate) {+ throw new AwsException("AssociationAlreadyExists",+ "An association already exists for document " + name + " with the given targets.", 400);+ }+ }++ String associationId = UUID.randomUUID().toString();+ Instant now = Instant.now();++ SsmAssociation association = new SsmAssociation();+ association.setAssociationId(associationId);+ association.setAssociationName(associationName);+ association.setName(name);+ association.setDocumentVersion(documentVersion);+ association.setInstanceId(instanceId);+ association.setTargets(targets);+ association.setParameters(parameters);+ association.setScheduleExpression(scheduleExpression);+ association.setMaxErrors(maxErrors);+ association.setMaxConcurrency(maxConcurrency);+ association.setComplianceSeverity(complianceSeverity);+ association.setAssociationVersion("1");+ // Real SSM starts an association at "Pending" and transitions it to "Success"/"Failed" once+ // its execution engine runs it. This emulator has no execution engine, so it reports+ // "Success" immediately rather than modeling a state that would never change on its own.+ association.setStatus(new SsmAssociation.AssociationStatus("Success", "Success", now, null));+ association.setOverview(new SsmAssociation.AssociationOverview("Success", "Success"));+ association.setCreatedDate(now);+ association.setLastExecutionDate(now);++ associationStore.put(regionKey(region, associationId), association);+ LOG.infov("Created association {0} ({1}) for document {2} in region {3}",+ associationId, associationName, name, region);+ return association;+ }++ public synchronized SsmAssociation updateAssociation(+ String associationId,+ String associationName,+ String documentVersion,+ List<SsmAssociation.Target> targets,+ Map<String, List<String>> parameters,+ String scheduleExpression,+ String maxErrors,+ String maxConcurrency,+ String complianceSeverity,+ String region) {+ String storageKey = regionKey(region, associationId);+ SsmAssociation association = associationStore.get(storageKey)+ .orElseThrow(() -> new AwsException("AssociationDoesNotExist",+ "The specified association does not exist.", 400));++ if (documentVersion != null) {+ validateDocumentVersion(getDocument(association.getName(), region), documentVersion);+ }++ if (associationName != null) association.setAssociationName(associationName);+ if (documentVersion != null) association.setDocumentVersion(documentVersion);+ if (targets != null) association.setTargets(targets);+ if (parameters != null) association.setParameters(parameters);+ if (scheduleExpression != null) association.setScheduleExpression(scheduleExpression);+ if (maxErrors != null) association.setMaxErrors(maxErrors);+ if (maxConcurrency != null) association.setMaxConcurrency(maxConcurrency);+ if (complianceSeverity != null) association.setComplianceSeverity(complianceSeverity);++ long currentVersion = parseAssociationVersion(association.getAssociationVersion());+ association.setAssociationVersion(String.valueOf(currentVersion + 1));++ associationStore.put(storageKey, association);+ LOG.infov("Updated association {0} in region {1}", associationId, region);+ return association;+ }++ private static long parseAssociationVersion(String version) {+ try {+ return version == null ? 1 : Long.parseLong(version);+ } catch (NumberFormatException e) {+ return 1;+ }+ }++ public List<SsmAssociation> listAssociations(String region) {+ return listAssociations(region, Map.of());+ }++ public List<SsmAssociation> listAssociations(String region, Map<String, List<String>> filters) {+ String prefix = regionKey(region, "");+ List<SsmAssociation> associations = associationStore.scan(k -> k.startsWith(prefix));+ if (filters == null || filters.isEmpty()) {+ return associations;+ }++ List<String> instanceIdFilters = findFilterValues(filters, "InstanceId");+ List<String> associationIdFilters = findFilterValues(filters, "AssociationId");+ List<String> nameFilters = findFilterValues(filters, "Name");+ List<String> associationNameFilters = findFilterValues(filters, "AssociationName");++ return associations.stream()+ .filter(a -> instanceIdFilters.isEmpty() || instanceIdFilters.contains(a.getInstanceId()))+ .filter(a -> associationIdFilters.isEmpty() || associationIdFilters.contains(a.getAssociationId()))+ .filter(a -> nameFilters.isEmpty() || nameFilters.contains(a.getName()))+ .filter(a -> associationNameFilters.isEmpty() || associationNameFilters.contains(a.getAssociationName()))+ .toList();+ }++ public SsmAssociation describeAssociation(String associationId, String name, String instanceId, String region) {+ if (associationId != null && !associationId.isBlank()) {+ return associationStore.get(regionKey(region, associationId))+ .orElseThrow(() -> new AwsException("AssociationDoesNotExist",+ "The specified association does not exist.", 400));+ }+ if (name != null && instanceId != null) {+ String prefix = regionKey(region, "");+ return associationStore.scan(k -> k.startsWith(prefix)).stream()+ .filter(a -> Objects.equals(a.getName(), name) && Objects.equals(a.getInstanceId(), instanceId))+ .findFirst()+ .orElseThrow(() -> new AwsException("AssociationDoesNotExist",+ "The specified association does not exist.", 400));+ }+ throw new AwsException("ValidationException",+ "Either AssociationId or both Name and InstanceId must be specified.", 400);+ }++ public synchronized void deleteAssociation(String associationId, String name, String instanceId, String region) {+ SsmAssociation association = describeAssociation(associationId, name, instanceId, region);+ associationStore.delete(regionKey(region, association.getAssociationId()));+ LOG.infov("Deleted association {0} in region {1}", association.getAssociationId(), region);+ }+// ──────────────────────────── Patch Baselines ────────────────────────────// AWS provides a fixed set of AWS-owned predefined patch baselines (one default per operating// system). These are static reference data, not customer state, so they live in-memory only.diff --git a/src/main/java/io/github/hectorvent/floci/services/ssm/model/SsmAssociation.java b/src/main/java/io/github/hectorvent/floci/services/ssm/model/SsmAssociation.javanew file mode 100644index 0000000000..26cf3c28ee--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/ssm/model/SsmAssociation.java@@ -0,0 +1,364 @@+package io.github.hectorvent.floci.services.ssm.model;++import com.fasterxml.jackson.annotation.JsonIgnoreProperties;+import com.fasterxml.jackson.annotation.JsonProperty;+import io.quarkus.runtime.annotations.RegisterForReflection;++import java.time.Instant;+import java.util.List;+import java.util.Map;+import java.util.Objects;++@RegisterForReflection+@JsonIgnoreProperties(ignoreUnknown = true)+public class SsmAssociation {++ @JsonProperty("AssociationId")+ private String associationId;++ @JsonProperty("AssociationName")+ private String associationName;++ @JsonProperty("Name")+ private String name;++ @JsonProperty("DocumentVersion")+ private String documentVersion;++ @JsonProperty("InstanceId")+ private String instanceId;++ @JsonProperty("Targets")+ private List<Target> targets;++ @JsonProperty("Parameters")+ private Map<String, List<String>> parameters;++ @JsonProperty("ScheduleExpression")+ private String scheduleExpression;++ @JsonProperty("Status")+ private AssociationStatus status;++ @JsonProperty("Overview")+ private AssociationOverview overview;++ @JsonProperty("Date")+ private Instant createdDate;++ @JsonProperty("LastExecutionDate")+ private Instant lastExecutionDate;++ @JsonProperty("ComplianceSeverity")+ private String complianceSeverity;++ @JsonProperty("MaxConcurrency")+ private String maxConcurrency;++ @JsonProperty("MaxErrors")+ private String maxErrors;++ @JsonProperty("AssociationVersion")+ private String associationVersion;++ public SsmAssociation() {}++ public SsmAssociation(+ String associationId,+ String associationName,+ String name,+ String documentVersion,+ String instanceId,+ List<Target> targets,+ Map<String, List<String>> parameters,+ String scheduleExpression,+ AssociationStatus status,+ AssociationOverview overview,+ Instant createdDate,+ Instant lastExecutionDate,+ String complianceSeverity,+ String maxConcurrency,+ String maxErrors) {+ this.associationId = associationId;+ this.associationName = associationName;+ this.name = name;+ this.documentVersion = documentVersion;+ this.instanceId = instanceId;+ this.targets = targets;+ this.parameters = parameters;+ this.scheduleExpression = scheduleExpression;+ this.status = status;+ this.overview = overview;+ this.createdDate = createdDate;+ this.lastExecutionDate = lastExecutionDate;+ this.complianceSeverity = complianceSeverity;+ this.maxConcurrency = maxConcurrency;+ this.maxErrors = maxErrors;+ }++ public String getAssociationId() {+ return associationId;+ }++ public void setAssociationId(String associationId) {+ this.associationId = associationId;+ }++ public String getAssociationName() {+ return associationName;+ }++ public void setAssociationName(String associationName) {+ this.associationName = associationName;+ }++ public String getName() {+ return name;+ }++ public void setName(String name) {+ this.name = name;+ }++ public String getDocumentVersion() {+ return documentVersion;+ }++ public void setDocumentVersion(String documentVersion) {+ this.documentVersion = documentVersion;+ }++ public String getInstanceId() {+ return instanceId;+ }++ public void setInstanceId(String instanceId) {+ this.instanceId = instanceId;+ }++ public List<Target> getTargets() {+ return targets;+ }++ public void setTargets(List<Target> targets) {+ this.targets = targets;+ }++ public Map<String, List<String>> getParameters() {+ return parameters;+ }++ public void setParameters(Map<String, List<String>> parameters) {+ this.parameters = parameters;+ }++ public String getScheduleExpression() {+ return scheduleExpression;+ }++ public void setScheduleExpression(String scheduleExpression) {+ this.scheduleExpression = scheduleExpression;+ }++ public AssociationStatus getStatus() {+ return status;+ }++ public void setStatus(AssociationStatus status) {+ this.status = status;+ }++ public AssociationOverview getOverview() {+ return overview;+ }++ public void setOverview(AssociationOverview overview) {+ this.overview = overview;+ }++ public Instant getCreatedDate() {+ return createdDate;+ }++ public void setCreatedDate(Instant createdDate) {+ this.createdDate = createdDate;+ }++ public Instant getLastExecutionDate() {+ return lastExecutionDate;+ }++ public void setLastExecutionDate(Instant lastExecutionDate) {+ this.lastExecutionDate = lastExecutionDate;+ }++ public String getComplianceSeverity() {+ return complianceSeverity;+ }++ public void setComplianceSeverity(String complianceSeverity) {+ this.complianceSeverity = complianceSeverity;+ }++ public String getMaxConcurrency() {+ return maxConcurrency;+ }++ public void setMaxConcurrency(String maxConcurrency) {+ this.maxConcurrency = maxConcurrency;+ }++ public String getMaxErrors() {+ return maxErrors;+ }++ public void setMaxErrors(String maxErrors) {+ this.maxErrors = maxErrors;+ }++ public String getAssociationVersion() {+ return associationVersion;+ }++ public void setAssociationVersion(String associationVersion) {+ this.associationVersion = associationVersion;+ }++ @RegisterForReflection+ @JsonIgnoreProperties(ignoreUnknown = true)+ public static class Target {++ @JsonProperty("Key")+ private String key;++ @JsonProperty("Values")+ private List<String> values;++ public Target() {}++ public Target(String key, List<String> values) {+ this.key = key;+ this.values = values;+ }++ public String getKey() {+ return key;+ }++ public void setKey(String key) {+ this.key = key;+ }++ public List<String> getValues() {+ return values;+ }++ public void setValues(List<String> values) {+ this.values = values;+ }++ @Override+ public boolean equals(Object o) {+ if (this == o) return true;+ if (!(o instanceof Target target)) return false;+ return Objects.equals(key, target.key) && Objects.equals(values, target.values);+ }++ @Override+ public int hashCode() {+ return Objects.hash(key, values);+ }+ }++ @RegisterForReflection+ @JsonIgnoreProperties(ignoreUnknown = true)+ public static class AssociationOverview {++ @JsonProperty("Status")+ private String status;++ @JsonProperty("DetailedStatus")+ private String detailedStatus;++ public AssociationOverview() {}++ public AssociationOverview(String status, String detailedStatus) {+ this.status = status;+ this.detailedStatus = detailedStatus;+ }++ public String getStatus() {+ return status;+ }++ public void setStatus(String status) {+ this.status = status;+ }++ public String getDetailedStatus() {+ return detailedStatus;+ }++ public void setDetailedStatus(String detailedStatus) {+ this.detailedStatus = detailedStatus;+ }+ }++ @RegisterForReflection+ @JsonIgnoreProperties(ignoreUnknown = true)+ public static class AssociationStatus {++ @JsonProperty("Name")+ private String name;++ @JsonProperty("Message")+ private String message;++ @JsonProperty("Date")+ private Instant date;++ @JsonProperty("AdditionalInfo")+ private String additionalInfo;++ public AssociationStatus() {}++ public AssociationStatus(String name, String message, Instant date, String additionalInfo) {+ this.name = name;+ this.message = message;+ this.date = date;+ this.additionalInfo = additionalInfo;+ }++ public String getName() {+ return name;+ }++ public void setName(String name) {+ this.name = name;+ }++ public String getMessage() {+ return message;+ }++ public void setMessage(String message) {+ this.message = message;+ }++ public Instant getDate() {+ return date;+ }++ public void setDate(Instant date) {+ this.date = date;+ }++ public String getAdditionalInfo() {+ return additionalInfo;+ }++ public void setAdditionalInfo(String additionalInfo) {+ this.additionalInfo = additionalInfo;+ }+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/ssm/model/SsmDocument.java b/src/main/java/io/github/hectorvent/floci/services/ssm/model/SsmDocument.javaindex e978dd9eb1..83e77c8f1d 100644--- a/src/main/java/io/github/hectorvent/floci/services/ssm/model/SsmDocument.java+++ b/src/main/java/io/github/hectorvent/floci/services/ssm/model/SsmDocument.java@@ -5,6 +5,9 @@ import com.fasterxml.jackson.annotation.JsonProperty;import io.quarkus.runtime.annotations.RegisterForReflection;import java.time.Instant;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;@RegisterForReflection@JsonIgnoreProperties(ignoreUnknown = true)@@ -28,6 +31,21 @@ public class SsmDocument {@JsonProperty("CreatedDate")private Instant createdDate;+ @JsonProperty("Owner")+ private String owner;++ @JsonProperty("SchemaVersion")+ private String schemaVersion = "1.0";++ @JsonProperty("DocumentFormat")+ private String documentFormat = "JSON";++ @JsonProperty("PlatformTypes")+ private List<String> platformTypes = List.of("Windows", "Linux", "MacOS");++ @JsonProperty("Versions")+ private Map<String, String> versions = new LinkedHashMap<>();+public SsmDocument() {}public SsmDocument(String name, String content, String documentType) {@@ -36,6 +54,9 @@ public class SsmDocument {this.documentType = documentType;this.documentVersion = 1;this.createdDate = Instant.now();+ if (content != null) {+ this.versions.put("1", content);+ }}public String getName() { return name; }@@ -55,4 +76,84 @@ public class SsmDocument {public Instant getCreatedDate() { return createdDate; }public void setCreatedDate(Instant createdDate) { this.createdDate = createdDate; }++ public String getOwner() { return owner; }+ public void setOwner(String owner) { this.owner = owner; }++ public String getSchemaVersion() { return schemaVersion; }+ public void setSchemaVersion(String schemaVersion) { this.schemaVersion = schemaVersion; }++ public String getDocumentFormat() { return documentFormat; }+ public void setDocumentFormat(String documentFormat) { this.documentFormat = documentFormat; }++ public List<String> getPlatformTypes() { return platformTypes; }+ public void setPlatformTypes(List<String> platformTypes) { this.platformTypes = platformTypes; }++ public Map<String, String> getVersions() {+ if (versions == null) {+ versions = new LinkedHashMap<>();+ }+ if (versions.isEmpty() && content != null) {+ versions.put(String.valueOf(documentVersion > 0 ? documentVersion : 1), content);+ }+ return versions;+ }++ public void setVersions(Map<String, String> versions) {+ this.versions = versions != null ? new LinkedHashMap<>(versions) : new LinkedHashMap<>();+ }++ /**+ * Whether {@code version} could ever have existed on this document — a reference check with+ * no content implied. A document persisted before {@link #versions} was introduced backfills+ * only its current version's content (the older content was never retained), so a document+ * already at version 3 when this field shipped has no recorded content for "1" or "2" even+ * though both were real, valid versions. Falling back to a numeric range check (rather than+ * requiring map membership) keeps those legacy version numbers resolvable — e.g. an+ * association's {@code DocumentVersion} pointing at "1" is a legitimate reference even though+ * this store cannot return "1"'s actual content.+ *+ * <p>Use this only where no content is returned to the caller (association creation/update).+ * For anything that returns document content, use {@link #hasRetainedContent} instead —+ * substituting a different version's content here would mislabel it as the requested one.+ *+ * <p><b>This intentionally diverges from {@link #hasRetainedContent} for a legacy gap+ * version</b>: an association may reference "1" successfully while a later+ * {@code GetDocument(DocumentVersion="1")} on the same document 400s. That is not a bug to+ * reconcile by tightening this method or loosening {@code hasRetainedContent} — content for+ * that version was never captured and cannot be recovered, so the only two alternatives are+ * both worse: rejecting the association reference blocks a legitimate operation for no benefit+ * (the association does not need the content), and fabricating content for+ * {@code GetDocument} would silently mislabel one version's content as another's. Keeping the+ * two checks separate is what lets each caller get the most honest answer its use case allows.+ */+ public boolean hasVersion(String version) {+ if (version == null) {+ return false;+ }+ if (getVersions().containsKey(version)) {+ return true;+ }+ try {+ long requested = Long.parseLong(version);+ return requested >= 1 && requested <= documentVersion;+ } catch (NumberFormatException e) {+ return false;+ }+ }++ /**+ * Whether this document's actual content for {@code version} was retained and can be+ * returned to a caller. Unlike {@link #hasVersion}, this does not treat a legacy version+ * predating {@link #versions} as available — GetDocument/DescribeDocument must not return+ * the current content mislabeled as an older version whose real content was never captured.+ */+ public boolean hasRetainedContent(String version) {+ return version != null && getVersions().containsKey(version);+ }++ /** Retained content for {@code version}, or {@code null} if it was never captured. */+ public String getContentForVersion(String version) {+ return getVersions().get(version);+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/ssm/SsmAssociationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ssm/SsmAssociationIntegrationTest.javanew file mode 100644index 0000000000..aca96202f7--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/ssm/SsmAssociationIntegrationTest.java@@ -0,0 +1,348 @@+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 static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.*;++@QuarkusTest+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class SsmAssociationIntegrationTest {++ private static final String SSM_CONTENT_TYPE = "application/x-amz-json-1.1";++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ @Test+ @Order(1)+ void createAssociation_DocumentNotFound() {+ given()+ .header("X-Amz-Target", "AmazonSSM.CreateAssociation")+ .contentType(SSM_CONTENT_TYPE)+ .body("""+ {+ "Name": "no-such-doc",+ "InstanceId": "i-1234567890abcdef0"+ }+ """)+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidDocument"));+ }++ @Test+ @Order(2)+ void createAssociation_MissingName() {+ given()+ .header("X-Amz-Target", "AmazonSSM.CreateAssociation")+ .contentType(SSM_CONTENT_TYPE)+ .body("""+ {+ "InstanceId": "i-1234567890abcdef0"+ }+ """)+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("ValidationException"));+ }++ @Test+ @Order(3)+ void associationLifecycle() {+ // First create a document: assoc-test-doc (DocumentType: "Command", valid content)+ given()+ .header("X-Amz-Target", "AmazonSSM.CreateDocument")+ .contentType(SSM_CONTENT_TYPE)+ .body("""+ {+ "Name": "assoc-test-doc",+ "DocumentType": "Command",+ "Content": "{\\"schemaVersion\\":\\"2.2\\",\\"mainSteps\\":[]}"+ }+ """)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("DocumentDescription.Name", equalTo("assoc-test-doc"));++ // Create association+ String associationId = given()+ .header("X-Amz-Target", "AmazonSSM.CreateAssociation")+ .contentType(SSM_CONTENT_TYPE)+ .body("""+ {+ "Name": "assoc-test-doc",+ "AssociationName": "my-assoc",+ "InstanceId": "i-1234567890abcdef0",+ "Parameters": {+ "commands": ["echo hello"]+ },+ "ScheduleExpression": "rate(30 minutes)"+ }+ """)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("AssociationDescription.Name", equalTo("assoc-test-doc"))+ .body("AssociationDescription.AssociationName", equalTo("my-assoc"))+ .body("AssociationDescription.Status.Name", equalTo("Success"))+ .extract().path("AssociationDescription.AssociationId");++ // List associations+ given()+ .header("X-Amz-Target", "AmazonSSM.ListAssociations")+ .contentType(SSM_CONTENT_TYPE)+ .body("{}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("Associations.AssociationId", hasItem(associationId))+ .body("Associations.Name", hasItem("assoc-test-doc"));++ // Describe association by AssociationId+ given()+ .header("X-Amz-Target", "AmazonSSM.DescribeAssociation")+ .contentType(SSM_CONTENT_TYPE)+ .body(String.format("""+ {+ "AssociationId": "%s"+ }+ """, associationId))+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("AssociationDescription.AssociationId", equalTo(associationId));++ // Update association+ given()+ .header("X-Amz-Target", "AmazonSSM.UpdateAssociation")+ .contentType(SSM_CONTENT_TYPE)+ .body(String.format("""+ {+ "AssociationId": "%s",+ "ScheduleExpression": "rate(1 hour)"+ }+ """, associationId))+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("AssociationDescription.AssociationId", equalTo(associationId))+ .body("AssociationDescription.ScheduleExpression", equalTo("rate(1 hour)"))+ .body("AssociationDescription.AssociationVersion", equalTo("2"));++ // Describe association by Name and InstanceId+ given()+ .header("X-Amz-Target", "AmazonSSM.DescribeAssociation")+ .contentType(SSM_CONTENT_TYPE)+ .body("""+ {+ "Name": "assoc-test-doc",+ "InstanceId": "i-1234567890abcdef0"+ }+ """)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("AssociationDescription.AssociationId", equalTo(associationId));++ // Delete association+ given()+ .header("X-Amz-Target", "AmazonSSM.DeleteAssociation")+ .contentType(SSM_CONTENT_TYPE)+ .body(String.format("""+ {+ "AssociationId": "%s"+ }+ """, associationId))+ .when()+ .post("/")+ .then()+ .statusCode(200);++ // Subsequent describe association returns 400+ given()+ .header("X-Amz-Target", "AmazonSSM.DescribeAssociation")+ .contentType(SSM_CONTENT_TYPE)+ .body(String.format("""+ {+ "AssociationId": "%s"+ }+ """, associationId))+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("AssociationDoesNotExist"));++ // Delete already deleted association returns 400+ given()+ .header("X-Amz-Target", "AmazonSSM.DeleteAssociation")+ .contentType(SSM_CONTENT_TYPE)+ .body(String.format("""+ {+ "AssociationId": "%s"+ }+ """, associationId))+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("AssociationDoesNotExist"));+ }++ @Test+ @Order(4)+ void createAssociation_Duplicate() {+ given()+ .header("X-Amz-Target", "AmazonSSM.CreateDocument")+ .contentType(SSM_CONTENT_TYPE)+ .body("""+ {+ "Name": "dup-assoc-doc",+ "DocumentType": "Command",+ "Content": "{\\"schemaVersion\\":\\"2.2\\",\\"mainSteps\\":[]}"+ }+ """)+ .when()+ .post("/")+ .then()+ .statusCode(200);++ given()+ .header("X-Amz-Target", "AmazonSSM.CreateAssociation")+ .contentType(SSM_CONTENT_TYPE)+ .body("""+ {+ "Name": "dup-assoc-doc",+ "InstanceId": "i-dupdupdupdupdup1"+ }+ """)+ .when()+ .post("/")+ .then()+ .statusCode(200);++ given()+ .header("X-Amz-Target", "AmazonSSM.CreateAssociation")+ .contentType(SSM_CONTENT_TYPE)+ .body("""+ {+ "Name": "dup-assoc-doc",+ "InstanceId": "i-dupdupdupdupdup1"+ }+ """)+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("AssociationAlreadyExists"));+ }++ @Test+ @Order(5)+ void createAssociation_DocumentVersionTargeting() {+ String docName = "assoc-ver-doc";+ given()+ .header("X-Amz-Target", "AmazonSSM.CreateDocument")+ .contentType(SSM_CONTENT_TYPE)+ .body(String.format("""+ {+ "Name": "%s",+ "DocumentType": "Command",+ "Content": "{\\"schemaVersion\\":\\"1.0\\"}"+ }+ """, docName))+ .when()+ .post("/")+ .then()+ .statusCode(200);++ // Update document to version 2+ given()+ .header("X-Amz-Target", "AmazonSSM.UpdateDocument")+ .contentType(SSM_CONTENT_TYPE)+ .body(String.format("""+ {+ "Name": "%s",+ "Content": "{\\"schemaVersion\\":\\"2.0\\"}"+ }+ """, docName))+ .when()+ .post("/")+ .then()+ .statusCode(200);++ // Target historical version 1: content was retained so association succeeds+ given()+ .header("X-Amz-Target", "AmazonSSM.CreateAssociation")+ .contentType(SSM_CONTENT_TYPE)+ .body(String.format("""+ {+ "Name": "%s",+ "AssociationName": "historical-assoc",+ "DocumentVersion": "1",+ "InstanceId": "i-hist1111111111111"+ }+ """, docName))+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("AssociationDescription.DocumentVersion", equalTo("1"));++ // Target version 2: succeeds+ given()+ .header("X-Amz-Target", "AmazonSSM.CreateAssociation")+ .contentType(SSM_CONTENT_TYPE)+ .body(String.format("""+ {+ "Name": "%s",+ "AssociationName": "v2-assoc",+ "DocumentVersion": "2",+ "InstanceId": "i-hist2222222222222"+ }+ """, docName))+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("AssociationDescription.DocumentVersion", equalTo("2"));++ // Non-existent version 99: throws InvalidDocumentVersion+ given()+ .header("X-Amz-Target", "AmazonSSM.CreateAssociation")+ .contentType(SSM_CONTENT_TYPE)+ .body(String.format("""+ {+ "Name": "%s",+ "AssociationName": "invalid-assoc",+ "DocumentVersion": "99",+ "InstanceId": "i-hist9999999999999"+ }+ """, docName))+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidDocumentVersion"));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/ssm/SsmDocumentLifecycleIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ssm/SsmDocumentLifecycleIntegrationTest.javaindex e9a1189b36..d759468d74 100644--- a/src/test/java/io/github/hectorvent/floci/services/ssm/SsmDocumentLifecycleIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ssm/SsmDocumentLifecycleIntegrationTest.java@@ -60,6 +60,65 @@ class SsmDocumentLifecycleIntegrationTest {@Test@Order(2)+ void listDocuments() {+ given()+ .header("X-Amz-Target", "AmazonSSM.ListDocuments")+ .contentType(SSM_CONTENT_TYPE)+ .body("{}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("DocumentIdentifiers.find { it.Name == 'floci-test-doc' }.Name", equalTo("floci-test-doc"))+ .body("DocumentIdentifiers.find { it.Name == 'floci-test-doc' }.DocumentType", equalTo("Command"))+ .body("DocumentIdentifiers.find { it.Name == 'floci-test-doc' }.DocumentVersion", equalTo("1"))+ .body("DocumentIdentifiers.find { it.Name == 'floci-test-doc' }.Owner", notNullValue())+ .body("DocumentIdentifiers.find { it.Name == 'floci-test-doc' }.PlatformTypes", hasItems("Windows", "Linux", "MacOS"));++ given()+ .header("X-Amz-Target", "AmazonSSM.ListDocuments")+ .contentType(SSM_CONTENT_TYPE)+ .body("""+ {+ "Filters": [+ {+ "Key": "Name",+ "Values": ["floci-test-doc"]+ }+ ]+ }+ """)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("DocumentIdentifiers.Name", hasItem("floci-test-doc"))+ .body("DocumentIdentifiers.find { it.Name == 'floci-test-doc' }.DocumentType", equalTo("Command"))+ .body("DocumentIdentifiers.find { it.Name == 'floci-test-doc' }.DocumentVersion", equalTo("1"))+ .body("DocumentIdentifiers.find { it.Name == 'floci-test-doc' }.PlatformTypes", hasItems("Windows", "Linux", "MacOS"));++ given()+ .header("X-Amz-Target", "AmazonSSM.ListDocuments")+ .contentType(SSM_CONTENT_TYPE)+ .body("""+ {+ "Filters": [+ {+ "Key": "Name",+ "Values": ["non-matching-doc"]+ }+ ]+ }+ """)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("DocumentIdentifiers", empty());+ }++ @Test+ @Order(3)void deleteDocument() {given().header("X-Amz-Target", "AmazonSSM.DeleteDocument")@@ -73,10 +132,20 @@ class SsmDocumentLifecycleIntegrationTest {.post("/").then().statusCode(200);++ given()+ .header("X-Amz-Target", "AmazonSSM.ListDocuments")+ .contentType(SSM_CONTENT_TYPE)+ .body("{}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("DocumentIdentifiers.findAll { it.Name == 'floci-test-doc' }", empty());}@Test- @Order(3)+ @Order(4)void describeMissingDocument() {given().header("X-Amz-Target", "AmazonSSM.DescribeDocument")@@ -94,7 +163,7 @@ class SsmDocumentLifecycleIntegrationTest {}@Test- @Order(4)+ @Order(5)void createDocumentRejectsNonStringName() {given().header("X-Amz-Target", "AmazonSSM.CreateDocument")@@ -112,4 +181,122 @@ class SsmDocumentLifecycleIntegrationTest {.statusCode(400).body("__type", equalTo("ValidationException"));}++ @Test+ @Order(6)+ void updateAndResolveDocumentVersions() {+ String docName = "doc-version-test";+ given()+ .header("X-Amz-Target", "AmazonSSM.CreateDocument")+ .contentType(SSM_CONTENT_TYPE)+ .body(String.format("""+ {+ "Name": "%s",+ "DocumentType": "Command",+ "Content": "{\\"schemaVersion\\":\\"1.0\\"}"+ }+ """, docName))+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("DocumentDescription.DocumentVersion", equalTo("1"));++ // Update document to version 2+ given()+ .header("X-Amz-Target", "AmazonSSM.UpdateDocument")+ .contentType(SSM_CONTENT_TYPE)+ .body(String.format("""+ {+ "Name": "%s",+ "Content": "{\\"schemaVersion\\":\\"2.0\\"}"+ }+ """, docName))+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("DocumentDescription.DocumentVersion", equalTo("2"));++ // Get historical version 1+ given()+ .header("X-Amz-Target", "AmazonSSM.GetDocument")+ .contentType(SSM_CONTENT_TYPE)+ .body(String.format("""+ {+ "Name": "%s",+ "DocumentVersion": "1"+ }+ """, docName))+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("DocumentVersion", equalTo("1"))+ .body("Content", equalTo("{\"schemaVersion\":\"1.0\"}"));++ // Get latest version 2+ given()+ .header("X-Amz-Target", "AmazonSSM.GetDocument")+ .contentType(SSM_CONTENT_TYPE)+ .body(String.format("""+ {+ "Name": "%s",+ "DocumentVersion": "2"+ }+ """, docName))+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("DocumentVersion", equalTo("2"))+ .body("Content", equalTo("{\"schemaVersion\":\"2.0\"}"));++ // Describe historical version 1+ given()+ .header("X-Amz-Target", "AmazonSSM.DescribeDocument")+ .contentType(SSM_CONTENT_TYPE)+ .body(String.format("""+ {+ "Name": "%s",+ "DocumentVersion": "1"+ }+ """, docName))+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("Document.DocumentVersion", equalTo("1"))+ .body("Document.Content", equalTo("{\"schemaVersion\":\"1.0\"}"));++ // Non-existent version throws InvalidDocumentVersion+ given()+ .header("X-Amz-Target", "AmazonSSM.GetDocument")+ .contentType(SSM_CONTENT_TYPE)+ .body(String.format("""+ {+ "Name": "%s",+ "DocumentVersion": "99"+ }+ """, docName))+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidDocumentVersion"));++ // Cleanup+ given()+ .header("X-Amz-Target", "AmazonSSM.DeleteDocument")+ .contentType(SSM_CONTENT_TYPE)+ .body(String.format("""+ {+ "Name": "%s"+ }+ """, docName))+ .when()+ .post("/")+ .then()+ .statusCode(200);+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/ssm/SsmIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ssm/SsmIntegrationTest.javaindex 4a546b59d2..914625341b 100644--- a/src/test/java/io/github/hectorvent/floci/services/ssm/SsmIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ssm/SsmIntegrationTest.java@@ -486,14 +486,18 @@ class SsmIntegrationTest {.body("BaselineId", startsWith("pb-"));}- // ── Read-only list operations for resources not modeled (empty results) ──-@Test- void listDocuments_returnsEmptyList() {+ void listDocuments_unmatchedNameFilterReturnsEmptyList() {given().header("X-Amz-Target", "AmazonSSM.ListDocuments").contentType(SSM_CONTENT_TYPE)- .body("{}")+ .body("""+ {+ "Filters": [+ {"Key": "Name", "Values": ["non-existent-doc-xyz-123"]}+ ]+ }+ """).when().post("/").then()@@ -553,11 +557,17 @@ class SsmIntegrationTest {}@Test- void listAssociations_returnsEmptyList() {+ void listAssociations_unmatchedInstanceFilterReturnsEmptyList() {given().header("X-Amz-Target", "AmazonSSM.ListAssociations").contentType(SSM_CONTENT_TYPE)- .body("{}")+ .body("""+ {+ "AssociationFilterList": [+ {"key": "InstanceId", "value": "i-nonexistent-000"}+ ]+ }+ """).when().post("/").then()@@ -566,6 +576,8 @@ class SsmIntegrationTest {.body("$", not(hasKey("NextToken")));}+ // ── Read-only list operations for resources not modeled (empty results) ──+@Testvoid describeMaintenanceWindows_returnsEmptyList() {given()diff --git a/src/test/java/io/github/hectorvent/floci/services/ssm/SsmServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ssm/SsmServiceTest.javaindex 2d338e0d7a..535ed343d6 100644--- a/src/test/java/io/github/hectorvent/floci/services/ssm/SsmServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ssm/SsmServiceTest.java@@ -7,11 +7,13 @@ import io.github.hectorvent.floci.core.storage.StorageBackend;import io.github.hectorvent.floci.services.ssm.model.Parameter;import io.github.hectorvent.floci.services.ssm.model.ParameterHistory;import io.github.hectorvent.floci.services.ssm.model.ServiceSetting;+import io.github.hectorvent.floci.services.ssm.model.SsmAssociation;import io.github.hectorvent.floci.services.ssm.model.SsmDocument;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;import java.util.List;+import java.util.Map;import java.util.Optional;import java.util.Set;import java.util.concurrent.CountDownLatch;@@ -454,4 +456,391 @@ class SsmServiceTest {"the delete's trailing permission cleanup must not remove the recreated "+ "document's new share");}++ @Test+ void testListDocuments() {+ ssmService.createDocument("Doc1", "{}", "Command", "us-east-1");+ ssmService.createDocument("Doc2", "{}", "Automation", "us-east-1");+ ssmService.createDocument("Doc3", "{}", "Command", "us-west-2");++ List<SsmDocument> eastDocs = ssmService.listDocuments("us-east-1", null);+ assertEquals(2, eastDocs.size());+ assertTrue(eastDocs.stream().anyMatch(d -> "Doc1".equals(d.getName())));+ assertTrue(eastDocs.stream().anyMatch(d -> "Doc2".equals(d.getName())));++ List<SsmDocument> westDocs = ssmService.listDocuments("us-west-2", Map.of());+ assertEquals(1, westDocs.size());+ assertEquals("Doc3", westDocs.get(0).getName());++ // Filter by DocumentType+ List<SsmDocument> commandDocs = ssmService.listDocuments("us-east-1", Map.of("DocumentType", List.of("Command")));+ assertEquals(1, commandDocs.size());+ assertEquals("Doc1", commandDocs.get(0).getName());++ // Filter by Name+ List<SsmDocument> namedDocs = ssmService.listDocuments("us-east-1", Map.of("Name", List.of("Doc2")));+ assertEquals(1, namedDocs.size());+ assertEquals("Doc2", namedDocs.get(0).getName());++ // Blank Name filter value must match nothing, not everything+ List<SsmDocument> blankNameDocs = ssmService.listDocuments("us-east-1", Map.of("Name", List.of("")));+ assertTrue(blankNameDocs.isEmpty());++ // Owner=Self/All/the caller's account id match every visible document (all are self-owned)+ List<SsmDocument> selfDocs = ssmService.listDocuments("us-east-1", Map.of("Owner", List.of("Self")));+ assertEquals(2, selfDocs.size());+ List<SsmDocument> allDocs = ssmService.listDocuments("us-east-1", Map.of("Owner", List.of("All")));+ assertEquals(2, allDocs.size());++ // Owner=Amazon/Public/another account id match none: no AWS-owned or cross-account documents+ List<SsmDocument> amazonDocs = ssmService.listDocuments("us-east-1", Map.of("Owner", List.of("Amazon")));+ assertTrue(amazonDocs.isEmpty());++ // Filter by PlatformTypes (all documents default to Windows/Linux/MacOS)+ List<SsmDocument> windowsDocs = ssmService.listDocuments("us-east-1", Map.of("PlatformTypes", List.of("Windows")));+ assertEquals(2, windowsDocs.size());+ List<SsmDocument> aixDocs = ssmService.listDocuments("us-east-1", Map.of("PlatformTypes", List.of("AIX")));+ assertTrue(aixDocs.isEmpty());+ }++ @Test+ void testListDocuments_LegacyNullOwnerMatchesSelfAndAccountId() {+ InMemoryStorage<String, SsmDocument> legacyDocumentStore = new InMemoryStorage<>();+ SsmDocument legacyDoc = new SsmDocument("LegacyDoc", "{}", "Command");+ legacyDocumentStore.put("us-east-1::LegacyDoc", legacyDoc);+ SsmService service = new SsmService(+ new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),+ legacyDocumentStore, new InMemoryStorage<>(), 5,+ new RegionResolver("us-east-1", "123456789012"));++ assertNull(legacyDoc.getOwner());+ List<SsmDocument> selfDocs = service.listDocuments("us-east-1", Map.of("Owner", List.of("Self")));+ assertEquals(1, selfDocs.size());+ assertEquals("123456789012", selfDocs.get(0).getOwner());++ List<SsmDocument> accountDocs = service.listDocuments("us-east-1", Map.of("Owner", List.of("123456789012")));+ assertEquals(1, accountDocs.size());+ assertEquals("123456789012", accountDocs.get(0).getOwner());++ List<SsmDocument> unfilteredDocs = service.listDocuments("us-east-1", null);+ assertEquals(1, unfilteredDocs.size());+ assertEquals("123456789012", unfilteredDocs.get(0).getOwner());++ assertTrue(service.listDocuments("us-east-1", Map.of("Owner", List.of("999999999999"))).isEmpty());+ }++ @Test+ void testCreateAssociation_Success() {+ String region = "us-east-1";+ ssmService.createDocument("AWS-RunShellScript", "{}", "Command", region);++ List<SsmAssociation.Target> targets = List.of(new SsmAssociation.Target("tag:Env", List.of("prod")));+ Map<String, List<String>> parameters = Map.of("commands", List.of("echo hello"));+ SsmAssociation assoc = ssmService.createAssociation(+ "AWS-RunShellScript",+ "test-association",+ "1",+ "i-1234567890abcdef0",+ targets,+ parameters,+ "rate(30 minutes)",+ region+ );++ assertNotNull(assoc.getAssociationId());+ assertFalse(assoc.getAssociationId().isBlank());+ assertEquals("test-association", assoc.getAssociationName());+ assertEquals("AWS-RunShellScript", assoc.getName());+ assertEquals("1", assoc.getDocumentVersion());+ assertEquals("i-1234567890abcdef0", assoc.getInstanceId());+ assertEquals(targets, assoc.getTargets());+ assertEquals(parameters, assoc.getParameters());+ assertEquals("rate(30 minutes)", assoc.getScheduleExpression());+ assertNotNull(assoc.getStatus());+ assertEquals("Success", assoc.getStatus().getName());+ assertNotNull(assoc.getOverview());+ assertEquals("Success", assoc.getOverview().getStatus());+ assertEquals("Success", assoc.getOverview().getDetailedStatus());+ assertNotNull(assoc.getCreatedDate());+ }++ @Test+ void testCreateAssociation_DocumentNotFound() {+ String region = "us-east-1";+ AwsException ex = assertThrows(AwsException.class, () ->+ ssmService.createAssociation("NonExistentDoc", "test-assoc", null, null, null, null, null, region));+ assertEquals("InvalidDocument", ex.getErrorCode());+ assertEquals(400, ex.getHttpStatus());+ }++ @Test+ void testListAssociations() {+ String east = "us-east-1";+ String west = "us-west-2";+ ssmService.createDocument("DocEast", "{}", "Command", east);+ ssmService.createDocument("DocWest", "{}", "Command", west);++ ssmService.createAssociation("DocEast", "assoc-1", null, "i-111", null, null, null, east);+ ssmService.createAssociation("DocEast", "assoc-2", null, "i-222", null, null, null, east);+ ssmService.createAssociation("DocWest", "assoc-3", null, "i-333", null, null, null, west);++ List<SsmAssociation> eastAssocs = ssmService.listAssociations(east);+ assertEquals(2, eastAssocs.size());+ assertTrue(eastAssocs.stream().anyMatch(a -> "assoc-1".equals(a.getAssociationName())));+ assertTrue(eastAssocs.stream().anyMatch(a -> "assoc-2".equals(a.getAssociationName())));++ List<SsmAssociation> westAssocs = ssmService.listAssociations(west);+ assertEquals(1, westAssocs.size());+ assertEquals("assoc-3", westAssocs.get(0).getAssociationName());++ // Filter by InstanceId+ List<SsmAssociation> filtered = ssmService.listAssociations(east, Map.of("InstanceId", List.of("i-111")));+ assertEquals(1, filtered.size());+ assertEquals("assoc-1", filtered.get(0).getAssociationName());++ // Blank InstanceId filter value must match nothing, not everything+ List<SsmAssociation> blankFiltered = ssmService.listAssociations(east, Map.of("InstanceId", List.of("")));+ assertTrue(blankFiltered.isEmpty());+ }++ @Test+ void testDescribeAssociation_ById() {+ String region = "us-east-1";+ ssmService.createDocument("MyDoc", "{}", "Command", region);+ SsmAssociation created = ssmService.createAssociation("MyDoc", "my-assoc", null, null, null, null, null, region);++ SsmAssociation found = ssmService.describeAssociation(created.getAssociationId(), null, null, region);+ assertEquals(created.getAssociationId(), found.getAssociationId());+ assertEquals("my-assoc", found.getAssociationName());++ // Region isolation+ AwsException exDiffRegion = assertThrows(AwsException.class, () ->+ ssmService.describeAssociation(created.getAssociationId(), null, null, "us-west-2"));+ assertEquals("AssociationDoesNotExist", exDiffRegion.getErrorCode());++ // Nonexistent ID+ AwsException exNotFound = assertThrows(AwsException.class, () ->+ ssmService.describeAssociation("non-existent-id", null, null, region));+ assertEquals("AssociationDoesNotExist", exNotFound.getErrorCode());+ assertEquals(400, exNotFound.getHttpStatus());+ }++ @Test+ void testDescribeAssociation_ByNameAndInstanceId() {+ String region = "us-east-1";+ ssmService.createDocument("MyDoc", "{}", "Command", region);+ SsmAssociation created = ssmService.createAssociation("MyDoc", "my-assoc", null, "i-12345", null, null, null, region);++ SsmAssociation found = ssmService.describeAssociation(null, "MyDoc", "i-12345", region);+ assertEquals(created.getAssociationId(), found.getAssociationId());+ assertEquals("i-12345", found.getInstanceId());++ // Nonexistent pair+ AwsException exNotFound = assertThrows(AwsException.class, () ->+ ssmService.describeAssociation(null, "MyDoc", "i-99999", region));+ assertEquals("AssociationDoesNotExist", exNotFound.getErrorCode());+ }++ @Test+ void testDeleteAssociation() {+ String region = "us-east-1";+ ssmService.createDocument("MyDoc", "{}", "Command", region);+ SsmAssociation created = ssmService.createAssociation("MyDoc", "my-assoc", null, "i-12345", null, null, null, region);++ // Delete by ID+ ssmService.deleteAssociation(created.getAssociationId(), null, null, region);++ // Subsequent describe throws AssociationDoesNotExist+ AwsException ex = assertThrows(AwsException.class, () ->+ ssmService.describeAssociation(created.getAssociationId(), null, null, region));+ assertEquals("AssociationDoesNotExist", ex.getErrorCode());++ // Deleting again throws AssociationDoesNotExist+ AwsException exDeleteAgain = assertThrows(AwsException.class, () ->+ ssmService.deleteAssociation(created.getAssociationId(), null, null, region));+ assertEquals("AssociationDoesNotExist", exDeleteAgain.getErrorCode());++ // Delete by Name and InstanceId+ SsmAssociation created2 = ssmService.createAssociation("MyDoc", "my-assoc-2", null, "i-54321", null, null, null, region);+ ssmService.deleteAssociation(null, "MyDoc", "i-54321", region);++ AwsException ex2 = assertThrows(AwsException.class, () ->+ ssmService.describeAssociation(created2.getAssociationId(), null, null, region));+ assertEquals("AssociationDoesNotExist", ex2.getErrorCode());+ }++ @Test+ void testCreateAssociation_MaxErrorsMaxConcurrencyComplianceSeverityRoundTrip() {+ String region = "us-east-1";+ ssmService.createDocument("MyDoc", "{}", "Command", region);++ SsmAssociation assoc = ssmService.createAssociation(+ "MyDoc", "my-assoc", null, "i-12345", null, null, null,+ "10%", "50%", "CRITICAL", region);++ assertEquals("1", assoc.getAssociationVersion());+ assertEquals("10%", assoc.getMaxErrors());+ assertEquals("50%", assoc.getMaxConcurrency());+ assertEquals("CRITICAL", assoc.getComplianceSeverity());++ SsmAssociation found = ssmService.describeAssociation(assoc.getAssociationId(), null, null, region);+ assertEquals("10%", found.getMaxErrors());+ assertEquals("50%", found.getMaxConcurrency());+ assertEquals("CRITICAL", found.getComplianceSeverity());+ }++ @Test+ void testCreateAssociation_ValidDocumentVersionSucceeds() {+ String region = "us-east-1";+ ssmService.createDocument("MyDoc", "{\"v\":1}", "Command", region);++ SsmAssociation assoc = ssmService.createAssociation(+ "MyDoc", "my-assoc", "1", "i-12345", null, null, null, region);+ assertEquals("1", assoc.getDocumentVersion());++ // Update document to version 2; prior version 1 content is retained in version history+ ssmService.updateDocument("MyDoc", "{\"v\":2}", region);++ SsmAssociation assocV1 = ssmService.createAssociation(+ "MyDoc", "my-assoc-v1", "1", "i-11111", null, null, null, region);+ assertEquals("1", assocV1.getDocumentVersion());++ SsmAssociation assocV2 = ssmService.createAssociation(+ "MyDoc", "my-assoc-v2", "2", "i-22222", null, null, null, region);+ assertEquals("2", assocV2.getDocumentVersion());++ SsmDocument doc = ssmService.getDocument("MyDoc", region);+ assertEquals("{\"v\":1}", doc.getContentForVersion("1"));+ assertEquals("{\"v\":2}", doc.getContentForVersion("2"));++ SsmAssociation latest = ssmService.createAssociation(+ "MyDoc", "my-assoc-latest", "$LATEST", "i-99999", null, null, null, region);+ assertEquals("$LATEST", latest.getDocumentVersion());+ }++ @Test+ void testCreateAssociation_InvalidDocumentVersionThrows() {+ String region = "us-east-1";+ ssmService.createDocument("MyDoc", "{}", "Command", region);++ AwsException exNonNumeric = assertThrows(AwsException.class, () ->+ ssmService.createAssociation("MyDoc", "my-assoc", "not-a-version", "i-12345", null, null, null, region));+ assertEquals("InvalidDocumentVersion", exNonNumeric.getErrorCode());+ assertEquals(400, exNonNumeric.getHttpStatus());++ AwsException exTooHigh = assertThrows(AwsException.class, () ->+ ssmService.createAssociation("MyDoc", "my-assoc", "99", "i-12345", null, null, null, region));+ assertEquals("InvalidDocumentVersion", exTooHigh.getErrorCode());+ }++ /**+ * A document persisted before {@code Versions} was tracked deserializes with an empty+ * versions map even though its DocumentVersion may already be past 1 (issue found in PR #3057+ * review): only its current content was ever retained, so versions "1"/"2" have no recorded+ * content, but they are still valid version numbers that must not be rejected as association+ * references. {@code getContentForVersion} must not fabricate content for them, though — a+ * later review comment on the same PR pointed out that substituting the current content would+ * mislabel it as an older version's real content in GetDocument/DescribeDocument.+ *+ * <p>A third review comment on the same thread pointed out the resulting asymmetry: this test+ * shows an association can reference "1" successfully while {@code hasRetainedContent("1")}+ * (what GetDocument/DescribeDocument check) is false for the same document. That divergence is+ * intentional, not a gap to close — see the javadoc on {@link SsmDocument#hasVersion} for why+ * both alternatives (rejecting the association, or fabricating GetDocument content) are worse.+ */+ @Test+ void testCreateAssociation_LegacyDocumentVersionWithoutHistoryIsStillValid() {+ InMemoryStorage<String, SsmDocument> legacyDocumentStore = new InMemoryStorage<>();+ SsmDocument legacyDoc = new SsmDocument();+ legacyDoc.setName("LegacyDoc");+ legacyDoc.setDocumentType("Command");+ legacyDoc.setContent("v3-content");+ legacyDoc.setDocumentVersion(3);+ legacyDocumentStore.put("us-east-1::LegacyDoc", legacyDoc);+ SsmService service = new SsmService(+ new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),+ legacyDocumentStore, new InMemoryStorage<>(), 5,+ new RegionResolver("us-east-1", "123456789012"));++ assertTrue(legacyDoc.hasVersion("1"));+ assertTrue(legacyDoc.hasVersion("2"));+ assertTrue(legacyDoc.hasVersion("3"));+ assertFalse(legacyDoc.hasVersion("4"));+ assertFalse(legacyDoc.hasRetainedContent("1"),+ "content for version 1 was never captured for a document already at version 3 when history tracking began");+ assertTrue(legacyDoc.hasRetainedContent("3"), "the current version's content is always retained");+ assertNull(legacyDoc.getContentForVersion("1"), "no content must be fabricated for an unretained version");++ SsmAssociation assoc = service.createAssociation(+ "LegacyDoc", "legacy-assoc", "1", "i-12345", null, null, null, "us-east-1");+ assertEquals("1", assoc.getDocumentVersion());+ }++ @Test+ void testUpdateAssociation_InvalidDocumentVersionThrows() {+ String region = "us-east-1";+ ssmService.createDocument("MyDoc", "{}", "Command", region);+ SsmAssociation created = ssmService.createAssociation("MyDoc", "my-assoc", null, "i-12345", null, null, null, region);++ AwsException ex = assertThrows(AwsException.class, () ->+ ssmService.updateAssociation(created.getAssociationId(), null, "99", null, null, null, null, null, null, region));+ assertEquals("InvalidDocumentVersion", ex.getErrorCode());++ // The association's DocumentVersion is unchanged after the rejected update+ SsmAssociation found = ssmService.describeAssociation(created.getAssociationId(), null, null, region);+ assertNull(found.getDocumentVersion());+ }++ @Test+ void testCreateAssociation_DuplicateInstanceThrowsAssociationAlreadyExists() {+ String region = "us-east-1";+ ssmService.createDocument("MyDoc", "{}", "Command", region);+ ssmService.createAssociation("MyDoc", "my-assoc", null, "i-12345", null, null, null, region);++ AwsException ex = assertThrows(AwsException.class, () ->+ ssmService.createAssociation("MyDoc", "my-assoc-2", null, "i-12345", null, null, null, region));+ assertEquals("AssociationAlreadyExists", ex.getErrorCode());+ assertEquals(400, ex.getHttpStatus());+ }++ @Test+ void testCreateAssociation_DuplicateTargetsThrowsAssociationAlreadyExists() {+ String region = "us-east-1";+ ssmService.createDocument("MyDoc", "{}", "Command", region);+ List<SsmAssociation.Target> targets = List.of(new SsmAssociation.Target("tag:Env", List.of("prod")));+ ssmService.createAssociation("MyDoc", "my-assoc", null, null, targets, null, null, region);++ AwsException ex = assertThrows(AwsException.class, () ->+ ssmService.createAssociation("MyDoc", "my-assoc-2", null, null,+ List.of(new SsmAssociation.Target("tag:Env", List.of("prod"))), null, null, region));+ assertEquals("AssociationAlreadyExists", ex.getErrorCode());+ }++ @Test+ void testUpdateAssociation_Success() {+ String region = "us-east-1";+ ssmService.createDocument("MyDoc", "{}", "Command", region);+ SsmAssociation created = ssmService.createAssociation("MyDoc", "my-assoc", null, "i-12345", null, null, null, region);+ assertEquals("1", created.getAssociationVersion());++ SsmAssociation updated = ssmService.updateAssociation(+ created.getAssociationId(), null, null, null, null,+ "rate(1 hour)", "5", null, null, region);++ assertEquals("rate(1 hour)", updated.getScheduleExpression());+ assertEquals("5", updated.getMaxErrors());+ assertEquals("2", updated.getAssociationVersion());++ SsmAssociation found = ssmService.describeAssociation(created.getAssociationId(), null, null, region);+ assertEquals("rate(1 hour)", found.getScheduleExpression());+ }++ @Test+ void testUpdateAssociation_NotFound() {+ String region = "us-east-1";+ AwsException ex = assertThrows(AwsException.class, () ->+ ssmService.updateAssociation("non-existent-id", null, null, null, null, null, null, null, null, region));+ assertEquals("AssociationDoesNotExist", ex.getErrorCode());+ assertEquals(400, ex.getHttpStatus());+ }}