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 bd2057c70e..15c81a02aa 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,12 +1,15 @@ package io.github.hectorvent.floci.services.ssm; import io.github.hectorvent.floci.core.common.AwsErrorResponse; +import io.github.hectorvent.floci.core.common.AwsException; 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 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.SsmDocument; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; @@ -23,6 +26,7 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.regex.Pattern; @ApplicationScoped public class SsmJsonHandler { @@ -60,9 +64,22 @@ public class SsmJsonHandler { case "ListCommandInvocations" -> handleListCommandInvocations(request, region); case "CancelCommand" -> handleCancelCommand(request, region); case "DescribeInstanceInformation" -> handleDescribeInstanceInformation(request, region); + // Service settings (LZA ssm-block-public-document-sharing) + case "GetServiceSetting" -> handleGetServiceSetting(request, region); + case "UpdateServiceSetting" -> handleUpdateServiceSetting(request, region); + case "ResetServiceSetting" -> handleResetServiceSetting(request, region); // Patch Manager (read-only: AWS-owned predefined baselines) case "DescribePatchBaselines" -> handleDescribePatchBaselines(request, region); case "GetDefaultPatchBaseline" -> handleGetDefaultPatchBaseline(request, region); + // Documents + case "GetDocument" -> handleGetDocument(request, region); + case "DescribeDocument" -> handleDescribeDocument(request, region); + case "DeleteDocument" -> handleDeleteDocument(request, region); + case "CreateDocument" -> handleCreateDocument(request, region); + case "UpdateDocument" -> handleUpdateDocument(request, region); + // Document share permissions + case "ModifyDocumentPermission" -> handleModifyDocumentPermission(request, region); + case "DescribeDocumentPermission" -> handleDescribeDocumentPermission(request, region); // Read-only list operations (resources not modeled: empty results) case "ListDocuments" -> handleListDocuments(request, region); case "ListAssociations" -> handleListAssociations(request, region); @@ -261,6 +278,227 @@ public class SsmJsonHandler { return Response.ok(response).build(); } + /** + * Reads the required {@code Name} member of a document operation. + * + *

{@code JsonNode.path(...).asText()} yields {@code ""} — not null — for an absent + * field, so without this guard a request with {@code Name} omitted builds the storage + * key {@code "|"} and surfaces a not-found error for a blank document name. + * Botocore constrains {@code DocumentName} to {@code ^[a-zA-Z0-9_\-.]{3,128}$}, so a + * blank name is a constraint violation, which AWS reports as {@code ValidationException} + * rather than any per-operation error (none of these operations model one that fits: + * {@code InvalidDocument} means "does not exist", and {@code CreateDocument} does not + * model it at all). + */ + /** Botocore's {@code DocumentName} pattern, verbatim from the model. */ + private static final Pattern DOCUMENT_NAME = Pattern.compile("^[a-zA-Z0-9_\\-.]{3,128}$"); + + /** + * {@code GetDocument} and {@code DescribeDocument} model a wider {@code Name} pattern than + * the other five document operations: botocore's {@code Name} member on these two allows + * {@code :} and {@code /}, because {@code DescribeDocument} accepts the document's full ARN + * when reading a document shared from another account. The other five reject that shape. + */ + private static final Pattern DOCUMENT_NAME_OR_ARN = Pattern.compile("^[a-zA-Z0-9_\\-.:/]{3,128}$"); + + private String requireDocumentName(JsonNode request) { + return requireDocumentName(request, DOCUMENT_NAME); + } + + private String requireDocumentNameOrArn(JsonNode request) { + return requireDocumentName(request, DOCUMENT_NAME_OR_ARN); + } + + private String requireDocumentName(JsonNode request, Pattern pattern) { + JsonNode nameNode = request.path("Name"); + String name = nameNode.asText(); + if (!nameNode.isTextual() || !pattern.matcher(name).matches()) { + throw new AwsException("ValidationException", + "1 validation error detected: Value '" + name + "' at 'name' failed to satisfy constraint: " + + "Member must satisfy regular expression pattern: " + pattern.pattern(), + 400); + } + return name; + } + + /** + * Reads the required {@code PermissionType} member of the two document-permission + * operations. Botocore models {@code DocumentPermissionType} as an enum with the single + * value {@code Share} and models {@code InvalidPermissionType} on both operations for + * anything else. An absent value is a missing required member, which AWS reports as + * {@code ValidationException} — the same treatment as an absent {@code Name}. + */ + private void requireSharePermissionType(JsonNode request) { + String permissionType = request.path("PermissionType").asText(); + if (permissionType == null || permissionType.isBlank()) { + throw new AwsException("ValidationException", + "1 validation error detected: Value null at 'permissionType' failed to satisfy " + + "constraint: Member must not be null", + 400); + } + if (!"Share".equals(permissionType)) { + throw new AwsException("InvalidPermissionType", + "The permission type isn't supported. Share is the only supported permission type.", + 400); + } + } + + /** + * The {@code DocumentType} enum, verbatim from the model. The value is stored on the document + * and echoed back by GetDocument, DescribeDocument and the create/update responses, so an + * unmodelled one is not merely accepted — it becomes the document's type for good. + */ + private static final Set DOCUMENT_TYPES = Set.of( + "Command", "Policy", "Automation", "Session", "Package", + "ApplicationConfiguration", "ApplicationConfigurationSchema", "DeploymentStrategy", + "ChangeCalendar", "Automation.ChangeTemplate", "ProblemAnalysis", + "ProblemAnalysisTemplate", "CloudFormation", "ConformancePackTemplate", + "QuickSetup", "ManualApprovalPolicy", "AutoApprovalPolicy"); + + /** {@code AccountIds} members are twelve digits or the case-insensitive wildcard {@code all}. */ + private static final Pattern ACCOUNT_ID = Pattern.compile("(?i)all|[0-9]{12}"); + + /** {@code AccountIdsToAdd} and {@code AccountIdsToRemove} are both capped at 20 members. */ + private static final int MAX_ACCOUNT_IDS = 20; + + /** + * Reads the optional {@code DocumentType}, defaulting to AWS's own {@code Command}. Anything + * outside the enum is a ValidationException rather than a stored document type nothing else + * in the emulator — or in AWS — will ever recognise. + */ + private String requireDocumentType(JsonNode request) { + String documentType = request.path("DocumentType").asText("Command"); + if (!DOCUMENT_TYPES.contains(documentType)) { + throw new AwsException("ValidationException", + "1 validation error detected: Value '" + documentType + "' at 'documentType' failed to " + + "satisfy constraint: Member must satisfy enum value set: " + DOCUMENT_TYPES, + 400); + } + return documentType; + } + + /** + * Reads one of the two {@code AccountIds} lists on ModifyDocumentPermission. The members are + * written straight into the document's share list, so an id that is not an account id would + * be reported back by DescribeDocumentPermission as though the share had happened. + */ + private List accountIds(JsonNode request, String field) { + List accountIds = new ArrayList<>(); + request.path(field).forEach(node -> accountIds.add(node.asText())); + if (accountIds.size() > MAX_ACCOUNT_IDS) { + throw new AwsException("ValidationException", + "1 validation error detected: Value at '" + decapitalize(field) + "' failed to satisfy " + + "constraint: Member must have length less than or equal to " + MAX_ACCOUNT_IDS, + 400); + } + for (String accountId : accountIds) { + if (!ACCOUNT_ID.matcher(accountId).matches()) { + throw new AwsException("ValidationException", + "1 validation error detected: Value '" + accountId + "' at '" + decapitalize(field) + + "' failed to satisfy constraint: Member must satisfy regular expression " + + "pattern: (?i)all|[0-9]{12}", + 400); + } + } + return accountIds; + } + + private static String decapitalize(String field) { + return Character.toLowerCase(field.charAt(0)) + field.substring(1); + } + + private Response handleGetDocument(JsonNode request, String region) { + String name = requireDocumentNameOrArn(request); + SsmDocument document = ssmService.getDocument(name, region); + + 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("Status", document.getStatus()); + return Response.ok(response).build(); + } + + private Response handleCreateDocument(JsonNode request, String region) { + String name = requireDocumentName(request); + String content = requireDocumentContent(request); + String documentType = requireDocumentType(request); + + SsmDocument document = ssmService.createDocument(name, content, documentType, region); + return Response.ok(documentDescriptionResponse(document)).build(); + } + + /** + * Reads the required {@code Content} member of CreateDocument/UpdateDocument. Botocore + * models {@code DocumentContent} as a string with {@code min: 1}, and both operations + * require it. {@code JsonNode.path(...).asText()} silently yields {@code ""} for either + * an absent member or a non-textual one (e.g. a JSON object sent instead of a JSON- or + * YAML-encoded string), so without this guard a malformed request stores or overwrites a + * document's content with an empty string instead of failing. + */ + private String requireDocumentContent(JsonNode request) { + JsonNode contentNode = request.path("Content"); + if (!contentNode.isTextual() || contentNode.asText().isBlank()) { + throw new AwsException("ValidationException", + "1 validation error detected: Value null at 'content' failed to satisfy " + + "constraint: Member must not be null", + 400); + } + return contentNode.asText(); + } + + private Response handleUpdateDocument(JsonNode request, String region) { + String name = requireDocumentName(request); + String content = requireDocumentContent(request); + + SsmDocument document = ssmService.updateDocument(name, content, region); + return Response.ok(documentDescriptionResponse(document)).build(); + } + + private ObjectNode documentDescriptionResponse(SsmDocument document) { + ObjectNode response = objectMapper.createObjectNode(); + ObjectNode description = objectMapper.createObjectNode(); + description.put("Name", document.getName()); + description.put("DocumentType", document.getDocumentType()); + description.put("DocumentVersion", String.valueOf(document.getDocumentVersion())); + description.put("Status", document.getStatus()); + description.put("LatestVersion", String.valueOf(document.getDocumentVersion())); + description.put("DefaultVersion", String.valueOf(document.getDocumentVersion())); + response.set("DocumentDescription", description); + return response; + } + + private Response handleModifyDocumentPermission(JsonNode request, String region) { + String name = requireDocumentName(request); + requireSharePermissionType(request); + List accountIdsToAdd = accountIds(request, "AccountIdsToAdd"); + List accountIdsToRemove = accountIds(request, "AccountIdsToRemove"); + + ssmService.modifyDocumentPermission(name, accountIdsToAdd, accountIdsToRemove, region); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + private Response handleDescribeDocumentPermission(JsonNode request, String region) { + String name = requireDocumentName(request); + requireSharePermissionType(request); + List accountIds = ssmService.describeDocumentPermission(name, region); + + ObjectNode response = objectMapper.createObjectNode(); + ArrayNode ids = objectMapper.createArrayNode(); + accountIds.forEach(ids::add); + response.set("AccountIds", ids); + ArrayNode sharingInfo = objectMapper.createArrayNode(); + for (String accountId : accountIds) { + ObjectNode info = objectMapper.createObjectNode(); + info.put("AccountId", accountId); + info.put("SharedDocumentVersion", "$DEFAULT"); + sharingInfo.add(info); + } + response.set("AccountSharingInfoList", sharingInfo); + return Response.ok(response).build(); + } + private Response handleListDocuments(JsonNode request, String region) { // SSM documents are not modeled: return an empty list. ObjectNode response = objectMapper.createObjectNode(); @@ -343,6 +581,62 @@ public class SsmJsonHandler { return node; } + // ── Service settings ─────────────────────────────────────────────────── + + /** + * Reads the required {@code SettingId} member shared by Get/Update/ResetServiceSetting. + * Botocore requires it on all three operations; an absent or blank value is a missing + * required member (ValidationException), not an unknown setting (ServiceSettingNotFound) — + * the same distinction the document operations draw between a missing {@code Name} and one + * that does not resolve. + */ + private String requireSettingId(JsonNode request) { + String settingId = request.path("SettingId").asText(); + if (settingId == null || settingId.isBlank()) { + throw new AwsException("ValidationException", + "1 validation error detected: Value null at 'settingId' failed to satisfy " + + "constraint: Member must not be null", + 400); + } + return settingId; + } + + private Response handleGetServiceSetting(JsonNode request, String region) { + String settingId = requireSettingId(request); + ServiceSetting setting = ssmService.getServiceSetting(settingId, region); + + ObjectNode response = objectMapper.createObjectNode(); + response.set("ServiceSetting", serviceSettingToNode(setting)); + return Response.ok(response).build(); + } + + private Response handleUpdateServiceSetting(JsonNode request, String region) { + String settingId = requireSettingId(request); + String settingValue = request.path("SettingValue").asText(); + ssmService.updateServiceSetting(settingId, settingValue, region); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + private Response handleResetServiceSetting(JsonNode request, String region) { + String settingId = requireSettingId(request); + ServiceSetting setting = ssmService.resetServiceSetting(settingId, region); + + ObjectNode response = objectMapper.createObjectNode(); + response.set("ServiceSetting", serviceSettingToNode(setting)); + return Response.ok(response).build(); + } + + private ObjectNode serviceSettingToNode(ServiceSetting s) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("SettingId", s.getSettingId()); + node.put("SettingValue", s.getSettingValue()); + node.put("LastModifiedDate", s.getLastModifiedDate().toEpochMilli() / 1000.0); + node.put("LastModifiedUser", s.getLastModifiedUser()); + node.put("ARN", s.getArn()); + node.put("Status", s.getStatus()); + return node; + } + // ── Agent registration ───────────────────────────────────────────────── private Response handleUpdateInstanceInformation(JsonNode request, String region) { @@ -499,4 +793,28 @@ public class SsmJsonHandler { if (info.getRegistrationDate() != null) node.put("RegistrationDate", info.getRegistrationDate().toEpochMilli() / 1000.0); return node; } + + private Response handleDescribeDocument(JsonNode request, String region) { + String name = requireDocumentNameOrArn(request); + SsmDocument document = ssmService.getDocument(name, region); + + 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("Status", document.getStatus()); + if (document.getCreatedDate() != null) { + documentNode.put("CreatedDate", document.getCreatedDate().toString()); + } + response.set("Document", documentNode); + return Response.ok(response).build(); + } + + private Response handleDeleteDocument(JsonNode request, String region) { + String name = requireDocumentName(request); + ssmService.deleteDocument(name, region); + return Response.ok(objectMapper.createObjectNode()).build(); + } } 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.java index 406d580206..a71b1cf2b7 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 @@ -3,11 +3,14 @@ package io.github.hectorvent.floci.services.ssm; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.storage.InMemoryStorage; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; 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.SsmDocument; import com.fasterxml.jackson.core.type.TypeReference; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; @@ -27,8 +30,22 @@ public class SsmService implements ResourceProvider { private static final Logger LOG = Logger.getLogger(SsmService.class); + /** + * Account-default values for the service settings floci models. AWS rejects + * unknown setting ids with ServiceSettingNotFound; so do we. + */ + private static final Map SERVICE_SETTING_DEFAULTS = Map.of( + "/ssm/documents/console/public-sharing-permission", "Enable", + "/ssm/parameter-store/default-parameter-tier", "Standard", + "/ssm/parameter-store/high-throughput-enabled", "false", + "/ssm/managed-instance/activation-tier", "standard" + ); + private final StorageBackend parameterStore; private final StorageBackend> historyStore; + private final StorageBackend> documentPermissionStore; + private final StorageBackend documentStore; + private final StorageBackend serviceSettingStore; private final int maxParameterHistory; private final RegionResolver regionResolver; @@ -41,6 +58,15 @@ public class SsmService implements ResourceProvider { storageFactory.create("ssm", "ssm-history.json", new TypeReference<>() { }), + storageFactory.create("ssm", "ssm-document-permissions.json", + new TypeReference<>() { + }), + storageFactory.create("ssm", "ssm-documents.json", + new TypeReference<>() { + }), + storageFactory.create("ssm", "ssm-service-settings.json", + new TypeReference<>() { + }), config.services().ssm().maxParameterHistory(), regionResolver ); @@ -51,16 +77,35 @@ public class SsmService implements ResourceProvider { */ SsmService(StorageBackend parameterStore, StorageBackend> historyStore, + StorageBackend> documentPermissionStore, int maxParameterHistory) { - this(parameterStore, historyStore, maxParameterHistory, + this(parameterStore, historyStore, documentPermissionStore, new InMemoryStorage<>(), + new InMemoryStorage<>(), maxParameterHistory, + new RegionResolver("us-east-1", "000000000000")); + } + + /** + * Package-private constructor for testing without CDI. + */ + SsmService(StorageBackend parameterStore, + StorageBackend> historyStore, + int maxParameterHistory) { + this(parameterStore, historyStore, new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), maxParameterHistory, new RegionResolver("us-east-1", "000000000000")); } SsmService(StorageBackend parameterStore, StorageBackend> historyStore, + StorageBackend> documentPermissionStore, + StorageBackend documentStore, + StorageBackend serviceSettingStore, int maxParameterHistory, RegionResolver regionResolver) { this.parameterStore = parameterStore; this.historyStore = historyStore; + this.documentPermissionStore = documentPermissionStore; + this.documentStore = documentStore; + this.serviceSettingStore = serviceSettingStore; this.maxParameterHistory = maxParameterHistory; this.regionResolver = regionResolver; } @@ -248,6 +293,88 @@ public class SsmService implements ResourceProvider { LOG.debugv("Removed tags from parameter: {0}", resourceId); } + // ──────────────────────── Documents and Share Permissions ──────────────── + // Documents live in documentStore; share state is kept alongside it in + // documentPermissionStore so callers like LZA's Custom::SSMShareDocument handler + // 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.) + + public SsmDocument getDocument(String name, String region) { + return documentStore.get(regionKey(region, name)) + .orElseThrow(() -> new AwsException("InvalidDocument", + "Document " + name + " does not exist.", 400)); + } + + public synchronized SsmDocument createDocument(String name, String content, String documentType, String region) { + String storageKey = regionKey(region, name); + if (documentStore.get(storageKey).isPresent()) { + throw new AwsException("DocumentAlreadyExists", + "Document " + name + " already exists.", 400); + } + SsmDocument document = new SsmDocument(name, content, documentType); + documentStore.put(storageKey, document); + return document; + } + + public SsmDocument updateDocument(String name, String content, String region) { + String storageKey = regionKey(region, name); + SsmDocument document = documentStore.get(storageKey) + .orElseThrow(() -> new AwsException("InvalidDocument", + "Document " + name + " does not exist.", 400)); + if (Objects.equals(document.getContent(), content)) { + throw new AwsException("DuplicateDocumentContent", + "The content of the association document matches another document. " + + "Change the content of the document and try again.", 400); + } + document.setContent(content); + document.setDocumentVersion(document.getDocumentVersion() + 1); + documentStore.put(storageKey, document); + return document; + } + + /** + * Lists the accounts a document is shared with. AWS raises InvalidDocument for a + * document that does not exist rather than returning an empty list, so the document + * is resolved first. + */ + public List describeDocumentPermission(String name, String region) { + getDocument(name, region); + return documentPermissionStore.get(regionKey(region, name)) + .map(List::copyOf) + .orElse(List.of()); + } + + /** + * Shares (or un-shares) a document with other accounts. + * + *

Only the document's owner may share it. Ownership here is the storage + * partition: {@code documentStore} is an {@code AccountAwareStorageBackend}, whose key + * prefix is the caller's account from {@code RequestContext} — the same resolution + * {@code RegionResolver.getAccountId()} performs — so {@link #getDocument} can only + * resolve a document in the caller's own partition. A caller that does not own the + * document therefore gets InvalidDocument, which is AWS's answer for a document the + * caller cannot see. Deriving the check from the partition rather than a second stored + * owner field keeps the guard and the storage scope from ever disagreeing. + */ + public synchronized void modifyDocumentPermission(String name, List accountIdsToAdd, + List accountIdsToRemove, String region) { + getDocument(name, region); + String storageKey = regionKey(region, name); + List accountIds = new ArrayList<>( + documentPermissionStore.get(storageKey).orElse(List.of())); + for (String accountId : accountIdsToAdd) { + if (!accountIds.contains(accountId)) { + accountIds.add(accountId); + } + } + accountIds.removeAll(accountIdsToRemove); + documentPermissionStore.put(storageKey, accountIds); + LOG.debugv("Modified document permission for {0}: {1} account(s) shared", name, accountIds.size()); + } + // ──────────────────────────── 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. @@ -324,6 +451,58 @@ public class SsmService implements ResourceProvider { "No default patch baseline exists for operating system " + os, 400)); } + /** + * Read a service setting for the calling account. Never-customized settings + * report their account default with status "Default". + */ + public ServiceSetting getServiceSetting(String settingId, String region) { + String defaultValue = requireKnownSetting(settingId); + return serviceSettingStore.get(settingKey(region, settingId)) + .orElseGet(() -> defaultSetting(settingId, defaultValue, region)); + } + + public void updateServiceSetting(String settingId, String settingValue, String region) { + requireKnownSetting(settingId); + ServiceSetting setting = new ServiceSetting(settingId, settingValue, + settingArn(settingId, region), "Customized", + "arn:aws:iam::" + regionResolver.getAccountId() + ":root"); + serviceSettingStore.put(settingKey(region, settingId), setting); + } + + public ServiceSetting resetServiceSetting(String settingId, String region) { + String defaultValue = requireKnownSetting(settingId); + serviceSettingStore.delete(settingKey(region, settingId)); + return defaultSetting(settingId, defaultValue, region); + } + + private String requireKnownSetting(String settingId) { + String defaultValue = SERVICE_SETTING_DEFAULTS.get(settingId); + if (defaultValue == null) { + throw new AwsException("ServiceSettingNotFound", + "The specified service setting was not found: " + settingId, 400); + } + return defaultValue; + } + + private ServiceSetting defaultSetting(String settingId, String defaultValue, String region) { + return new ServiceSetting(settingId, defaultValue, settingArn(settingId, region), + "Default", "System"); + } + + /** + * Service settings are per-account per-region: LZA assumes a role into each + * member account before updating, so the caller's resolved account scopes the key. + */ + private String settingKey(String region, String settingId) { + return regionResolver.getAccountId() + "::" + regionKey(region, settingId); + } + + private String settingArn(String settingId, String region) { + // Setting ids begin with "/", so concatenation yields .../servicesetting/ssm/... + return "arn:aws:ssm:" + region + ":" + regionResolver.getAccountId() + + ":servicesetting" + settingId; + } + private static String regionKey(String region, String name) { return region + "::" + name; } @@ -342,6 +521,16 @@ public class SsmService implements ResourceProvider { historyStore.put(storageKey, history); } + public synchronized void deleteDocument(String name, String region) { + String storageKey = regionKey(region, name); + if (!documentStore.get(storageKey).isPresent()) { + throw new AwsException("InvalidDocument", + "Document " + name + " does not exist.", 400); + } + documentStore.delete(storageKey); + documentPermissionStore.delete(storageKey); + } + // ─── Resource Explorer 2 ─────────────────────────────────────────────────── @Override diff --git a/src/main/java/io/github/hectorvent/floci/services/ssm/model/ServiceSetting.java b/src/main/java/io/github/hectorvent/floci/services/ssm/model/ServiceSetting.java new file mode 100644 index 0000000000..db10dcf769 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ssm/model/ServiceSetting.java @@ -0,0 +1,90 @@ +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; + +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class ServiceSetting { + + @JsonProperty("SettingId") + private String settingId; + + @JsonProperty("SettingValue") + private String settingValue; + + @JsonProperty("LastModifiedDate") + private Instant lastModifiedDate; + + @JsonProperty("LastModifiedUser") + private String lastModifiedUser; + + @JsonProperty("ARN") + private String arn; + + @JsonProperty("Status") + private String status; + + public ServiceSetting() {} + + public ServiceSetting(String settingId, String settingValue, String arn, String status, + String lastModifiedUser) { + this.settingId = settingId; + this.settingValue = settingValue; + this.arn = arn; + this.status = status; + this.lastModifiedUser = lastModifiedUser; + this.lastModifiedDate = Instant.now(); + } + + public String getSettingId() { + return settingId; + } + + public void setSettingId(String settingId) { + this.settingId = settingId; + } + + public String getSettingValue() { + return settingValue; + } + + public void setSettingValue(String settingValue) { + this.settingValue = settingValue; + } + + public Instant getLastModifiedDate() { + return lastModifiedDate; + } + + public void setLastModifiedDate(Instant lastModifiedDate) { + this.lastModifiedDate = lastModifiedDate; + } + + public String getLastModifiedUser() { + return lastModifiedUser; + } + + public void setLastModifiedUser(String lastModifiedUser) { + this.lastModifiedUser = lastModifiedUser; + } + + public String getArn() { + return arn; + } + + public void setArn(String arn) { + this.arn = arn; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } +} 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.java new file mode 100644 index 0000000000..e978dd9eb1 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ssm/model/SsmDocument.java @@ -0,0 +1,58 @@ +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; + +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class SsmDocument { + + @JsonProperty("Name") + private String name; + + @JsonProperty("Content") + private String content; + + @JsonProperty("DocumentType") + private String documentType; + + @JsonProperty("DocumentVersion") + private long documentVersion; + + @JsonProperty("Status") + private String status = "Active"; + + @JsonProperty("CreatedDate") + private Instant createdDate; + + public SsmDocument() {} + + public SsmDocument(String name, String content, String documentType) { + this.name = name; + this.content = content; + this.documentType = documentType; + this.documentVersion = 1; + this.createdDate = Instant.now(); + } + + public String getName() { return name; } + public void setName(String name) { this.name = name; } + + public String getContent() { return content; } + public void setContent(String content) { this.content = content; } + + public String getDocumentType() { return documentType; } + public void setDocumentType(String documentType) { this.documentType = documentType; } + + public long getDocumentVersion() { return documentVersion; } + public void setDocumentVersion(long documentVersion) { this.documentVersion = documentVersion; } + + public String getStatus() { return status; } + public void setStatus(String status) { this.status = status; } + + public Instant getCreatedDate() { return createdDate; } + public void setCreatedDate(Instant createdDate) { this.createdDate = createdDate; } +} 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.java new file mode 100644 index 0000000000..e9a1189b36 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ssm/SsmDocumentLifecycleIntegrationTest.java @@ -0,0 +1,115 @@ +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 SsmDocumentLifecycleIntegrationTest { + + private static final String SSM_CONTENT_TYPE = "application/x-amz-json-1.1"; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + @Order(1) + void createAndDescribeDocument() { + given() + .header("X-Amz-Target", "AmazonSSM.CreateDocument") + .contentType(SSM_CONTENT_TYPE) + .body(""" + { + "Name": "floci-test-doc", + "DocumentType": "Command", + "Content": "{\\"schemaVersion\\":\\"2.2\\",\\"mainSteps\\":[]}" + } + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("DocumentDescription.Name", equalTo("floci-test-doc")) + .body("DocumentDescription.DocumentType", equalTo("Command")); + + given() + .header("X-Amz-Target", "AmazonSSM.DescribeDocument") + .contentType(SSM_CONTENT_TYPE) + .body(""" + { + "Name": "floci-test-doc" + } + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("Document.Name", equalTo("floci-test-doc")) + .body("Document.DocumentType", equalTo("Command")); + } + + @Test + @Order(2) + void deleteDocument() { + given() + .header("X-Amz-Target", "AmazonSSM.DeleteDocument") + .contentType(SSM_CONTENT_TYPE) + .body(""" + { + "Name": "floci-test-doc" + } + """) + .when() + .post("/") + .then() + .statusCode(200); + } + + @Test + @Order(3) + void describeMissingDocument() { + given() + .header("X-Amz-Target", "AmazonSSM.DescribeDocument") + .contentType(SSM_CONTENT_TYPE) + .body(""" + { + "Name": "floci-nonexistent-doc" + } + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidDocument")); + } + + @Test + @Order(4) + void createDocumentRejectsNonStringName() { + given() + .header("X-Amz-Target", "AmazonSSM.CreateDocument") + .contentType(SSM_CONTENT_TYPE) + .body(""" + { + "Name": 123, + "DocumentType": "Command", + "Content": "{\\"schemaVersion\\":\\"2.2\\",\\"mainSteps\\":[]}" + } + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")); + } +} 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.java index 60d50f42a4..fffb9c4952 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 @@ -235,6 +235,109 @@ class SsmIntegrationTest { .body("InvalidParameters", contains("/missing")); } + // ── Service settings (LZA ssm-block-public-document-sharing) ── + + @Test + @Order(11) + void getServiceSettingDefault() { + given() + .header("X-Amz-Target", "AmazonSSM.GetServiceSetting") + .contentType(SSM_CONTENT_TYPE) + .body(""" + { "SettingId": "/ssm/documents/console/public-sharing-permission" } + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("ServiceSetting.SettingId", equalTo("/ssm/documents/console/public-sharing-permission")) + .body("ServiceSetting.SettingValue", equalTo("Enable")) + .body("ServiceSetting.Status", equalTo("Default")) + .body("ServiceSetting.ARN", endsWith(":servicesetting/ssm/documents/console/public-sharing-permission")) + .body("ServiceSetting.LastModifiedDate", notNullValue()); + } + + @Test + @Order(12) + void updateServiceSetting() { + given() + .header("X-Amz-Target", "AmazonSSM.UpdateServiceSetting") + .contentType(SSM_CONTENT_TYPE) + .body(""" + { + "SettingId": "/ssm/documents/console/public-sharing-permission", + "SettingValue": "Disable" + } + """) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .header("X-Amz-Target", "AmazonSSM.GetServiceSetting") + .contentType(SSM_CONTENT_TYPE) + .body(""" + { "SettingId": "/ssm/documents/console/public-sharing-permission" } + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("ServiceSetting.SettingValue", equalTo("Disable")) + .body("ServiceSetting.Status", equalTo("Customized")); + } + + @Test + @Order(13) + void resetServiceSetting() { + given() + .header("X-Amz-Target", "AmazonSSM.ResetServiceSetting") + .contentType(SSM_CONTENT_TYPE) + .body(""" + { "SettingId": "/ssm/documents/console/public-sharing-permission" } + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("ServiceSetting.SettingValue", equalTo("Enable")) + .body("ServiceSetting.Status", equalTo("Default")); + } + + @Test + @Order(14) + void getUnknownServiceSettingReturnsError() { + given() + .header("X-Amz-Target", "AmazonSSM.GetServiceSetting") + .contentType(SSM_CONTENT_TYPE) + .body(""" + { "SettingId": "/ssm/bogus/does-not-exist" } + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("ServiceSettingNotFound")); + } + + @Test + void serviceSettingOperations_missingSettingIdReturnsValidationException() { + for (String target : new String[]{"GetServiceSetting", "UpdateServiceSetting", "ResetServiceSetting"}) { + given() + .header("X-Amz-Target", "AmazonSSM." + target) + .contentType(SSM_CONTENT_TYPE) + .body(""" + { "SettingValue": "Enable" } + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")); + } + } + // ── Issue #956: DescribePatchBaselines / GetDefaultPatchBaseline (AWS-owned predefined) ── @Test @@ -334,6 +437,56 @@ class SsmIntegrationTest { .body("$", not(hasKey("NextToken"))); } + @Test + void documentPermission_modifyAndDescribeRoundTrip() { + given() + .header("X-Amz-Target", "AmazonSSM.CreateDocument") + .contentType(SSM_CONTENT_TYPE) + .body(""" + { + "Name": "AwsAccelerator-SessionManagerLogging", + "DocumentType": "Session", + "Content": "{\\"schemaVersion\\":\\"1.0\\"}" + } + """) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .header("X-Amz-Target", "AmazonSSM.ModifyDocumentPermission") + .contentType(SSM_CONTENT_TYPE) + .body(""" + { + "Name": "AwsAccelerator-SessionManagerLogging", + "PermissionType": "Share", + "AccountIdsToAdd": ["444444444444"] + } + """) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .header("X-Amz-Target", "AmazonSSM.DescribeDocumentPermission") + .contentType(SSM_CONTENT_TYPE) + .body(""" + { + "Name": "AwsAccelerator-SessionManagerLogging", + "PermissionType": "Share" + } + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("AccountIds", hasItem("444444444444")) + .body("AccountSharingInfoList[0].AccountId", equalTo("444444444444")) + .body("AccountSharingInfoList[0].SharedDocumentVersion", notNullValue()); + } + @Test void listAssociations_returnsEmptyList() { given() @@ -374,4 +527,631 @@ class SsmIntegrationTest { .statusCode(400) .body("__type", equalTo("UnsupportedOperation")); } + + @Test + void getDocument_unknownReturnsInvalidDocument() { + given() + .header("X-Amz-Target", "AmazonSSM.GetDocument") + .contentType(SSM_CONTENT_TYPE) + .body(""" + { + "Name": "No-Such-Document" + } + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidDocument")); + } + + @Test + void document_createGetUpdateRoundTrip() { + // Create — mirrors LZA's session-manager-settings Lambda (DocumentType Session) + given() + .header("X-Amz-Target", "AmazonSSM.CreateDocument") + .contentType(SSM_CONTENT_TYPE) + .body(""" + { + "Name": "SSM-SessionManagerRunShell", + "DocumentType": "Session", + "Content": "{\\"schemaVersion\\":\\"1.0\\",\\"inputs\\":{\\"runAsEnabled\\":false}}" + } + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("DocumentDescription.Name", equalTo("SSM-SessionManagerRunShell")) + .body("DocumentDescription.DocumentType", equalTo("Session")) + .body("DocumentDescription.DocumentVersion", equalTo("1")) + .body("DocumentDescription.Status", equalTo("Active")); + + given() + .header("X-Amz-Target", "AmazonSSM.GetDocument") + .contentType(SSM_CONTENT_TYPE) + .body(""" + { + "Name": "SSM-SessionManagerRunShell" + } + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("Name", equalTo("SSM-SessionManagerRunShell")) + .body("DocumentType", equalTo("Session")) + .body("DocumentVersion", equalTo("1")) + .body("Content", containsString("runAsEnabled")); + + // Update with changed content bumps the version + given() + .header("X-Amz-Target", "AmazonSSM.UpdateDocument") + .contentType(SSM_CONTENT_TYPE) + .body(""" + { + "Name": "SSM-SessionManagerRunShell", + "DocumentVersion": "$LATEST", + "Content": "{\\"schemaVersion\\":\\"1.0\\",\\"inputs\\":{\\"runAsEnabled\\":true}}" + } + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("DocumentDescription.DocumentVersion", equalTo("2")); + + // Update with identical content fails DuplicateDocumentContent + given() + .header("X-Amz-Target", "AmazonSSM.UpdateDocument") + .contentType(SSM_CONTENT_TYPE) + .body(""" + { + "Name": "SSM-SessionManagerRunShell", + "DocumentVersion": "$LATEST", + "Content": "{\\"schemaVersion\\":\\"1.0\\",\\"inputs\\":{\\"runAsEnabled\\":true}}" + } + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("DuplicateDocumentContent")); + } + + // ── Document parameter validation (botocore: DocumentName ^[a-zA-Z0-9_\-.]{3,128}$) ── + + @Test + void documentOperations_blankNameReturnsValidationException() { + for (String target : new String[]{ + "GetDocument", "DescribeDocument", "DeleteDocument", + "CreateDocument", "UpdateDocument"}) { + given() + .header("X-Amz-Target", "AmazonSSM." + target) + .contentType(SSM_CONTENT_TYPE) + .body("{}") + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")); + } + } + + @Test + void documentOperations_nameViolatingPatternReturnsValidationException() { + for (String target : new String[]{"DeleteDocument", "CreateDocument", "UpdateDocument"}) { + given() + .header("X-Amz-Target", "AmazonSSM." + target) + .contentType(SSM_CONTENT_TYPE) + .body(""" + { + "Name": "/floci/test-doc", + "Content": "{\\"schemaVersion\\":\\"1.0\\"}" + } + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")); + } + } + + // GetDocument/DescribeDocument model a wider Name pattern than the other five document + // operations (botocore: ^[a-zA-Z0-9_\-.:/]{3,128}$, vs ^[a-zA-Z0-9_\-.]{3,128}$ elsewhere) — + // DescribeDocument's own docs say Name is the document's ARN when reading a document shared + // from another account, so the read path must accept ARN shapes even though the other five + // reject them. + @Test + void getDocumentAndDescribeDocument_acceptArnShapedName() { + for (String target : new String[]{"GetDocument", "DescribeDocument"}) { + given() + .header("X-Amz-Target", "AmazonSSM." + target) + .contentType(SSM_CONTENT_TYPE) + .body(""" + { + "Name": "arn:aws:ssm:us-east-1:000000000000:document/No-Such-Document" + } + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidDocument")); + } + } + + @Test + void getDocumentAndDescribeDocument_stillRejectTrulyInvalidName() { + for (String target : new String[]{"GetDocument", "DescribeDocument"}) { + given() + .header("X-Amz-Target", "AmazonSSM." + target) + .contentType(SSM_CONTENT_TYPE) + .body(""" + { + "Name": "not a valid name!" + } + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")); + } + } + + @Test + void documentPermissionOperations_blankNameReturnsValidationException() { + for (String target : new String[]{ + "ModifyDocumentPermission", "DescribeDocumentPermission"}) { + given() + .header("X-Amz-Target", "AmazonSSM." + target) + .contentType(SSM_CONTENT_TYPE) + .body(""" + { "PermissionType": "Share" } + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")); + } + } + + @Test + void createDocument_missingContentReturnsValidationException() { + given() + .header("X-Amz-Target", "AmazonSSM.CreateDocument") + .contentType(SSM_CONTENT_TYPE) + .body(""" + { "Name": "Floci-Missing-Content-Doc" } + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")); + } + + @Test + void createDocument_nonTextContentReturnsValidationException() { + given() + .header("X-Amz-Target", "AmazonSSM.CreateDocument") + .contentType(SSM_CONTENT_TYPE) + .body(""" + { + "Name": "Floci-Object-Content-Doc", + "Content": {"schemaVersion": "2.2", "mainSteps": []} + } + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")); + } + + @Test + void updateDocument_missingContentReturnsValidationExceptionWithoutErasingExistingContent() { + given() + .header("X-Amz-Target", "AmazonSSM.CreateDocument") + .contentType(SSM_CONTENT_TYPE) + .body(""" + { + "Name": "Floci-Update-Missing-Content-Doc", + "Content": "{\\"schemaVersion\\":\\"1.0\\"}" + } + """) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .header("X-Amz-Target", "AmazonSSM.UpdateDocument") + .contentType(SSM_CONTENT_TYPE) + .body(""" + { "Name": "Floci-Update-Missing-Content-Doc" } + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")); + + given() + .header("X-Amz-Target", "AmazonSSM.GetDocument") + .contentType(SSM_CONTENT_TYPE) + .body(""" + { "Name": "Floci-Update-Missing-Content-Doc" } + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("Content", containsString("schemaVersion")); + } + + // ── PermissionType (botocore: required, enum with the single value "Share") ── + + @Test + void documentPermissionOperations_rejectUnsupportedPermissionType() { + for (String target : new String[]{ + "ModifyDocumentPermission", "DescribeDocumentPermission"}) { + given() + .header("X-Amz-Target", "AmazonSSM." + target) + .contentType(SSM_CONTENT_TYPE) + .body(""" + { + "Name": "Doc-That-Was-Never-Created", + "PermissionType": "Own" + } + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidPermissionType")); + } + } + + @Test + void documentPermissionOperations_missingPermissionTypeIsRejected() { + for (String target : new String[]{ + "ModifyDocumentPermission", "DescribeDocumentPermission"}) { + given() + .header("X-Amz-Target", "AmazonSSM." + target) + .contentType(SSM_CONTENT_TYPE) + .body(""" + { "Name": "Doc-That-Was-Never-Created" } + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")); + } + } + + @Test + void deleteDocument_clearsSharePermissionsSoARecreatedDocumentStartsUnshared() { + given() + .header("X-Amz-Target", "AmazonSSM.CreateDocument") + .contentType(SSM_CONTENT_TYPE) + .body(""" + { + "Name": "Floci-Recreated-Shared-Doc", + "Content": "{\\"schemaVersion\\":\\"1.0\\"}" + } + """) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .header("X-Amz-Target", "AmazonSSM.ModifyDocumentPermission") + .contentType(SSM_CONTENT_TYPE) + .body(""" + { + "Name": "Floci-Recreated-Shared-Doc", + "PermissionType": "Share", + "AccountIdsToAdd": ["444444444444"] + } + """) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .header("X-Amz-Target", "AmazonSSM.DeleteDocument") + .contentType(SSM_CONTENT_TYPE) + .body(""" + { "Name": "Floci-Recreated-Shared-Doc" } + """) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .header("X-Amz-Target", "AmazonSSM.CreateDocument") + .contentType(SSM_CONTENT_TYPE) + .body(""" + { + "Name": "Floci-Recreated-Shared-Doc", + "Content": "{\\"schemaVersion\\":\\"1.0\\"}" + } + """) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .header("X-Amz-Target", "AmazonSSM.DescribeDocumentPermission") + .contentType(SSM_CONTENT_TYPE) + .body(""" + { + "Name": "Floci-Recreated-Shared-Doc", + "PermissionType": "Share" + } + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("AccountIds", empty()); + } + + // ── Permission ops agree with the document store (botocore models InvalidDocument) ── + + @Test + void documentPermissionOperations_unknownDocumentReturnsInvalidDocument() { + for (String target : new String[]{ + "ModifyDocumentPermission", "DescribeDocumentPermission"}) { + given() + .header("X-Amz-Target", "AmazonSSM." + target) + .contentType(SSM_CONTENT_TYPE) + .body(""" + { + "Name": "Doc-That-Was-Never-Created", + "PermissionType": "Share", + "AccountIdsToAdd": ["444444444444"] + } + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidDocument")); + } + } + + /** + * Only the document's owner may share it. Ownership is the storage partition: + * the document store is account-aware, so another account's ModifyDocumentPermission + * cannot resolve the document and gets InvalidDocument — AWS's own answer for a + * document the caller cannot see. + */ + @Test + void modifyDocumentPermission_otherAccountCannotShareOwnersDocument() { + String ownerAuth = "AWS4-HMAC-SHA256 Credential=000000000001/20260215/us-east-1/ssm/aws4_request," + + " SignedHeaders=host, Signature=abc"; + String otherAuth = "AWS4-HMAC-SHA256 Credential=000000000002/20260215/us-east-1/ssm/aws4_request," + + " SignedHeaders=host, Signature=abc"; + + given() + .header("Authorization", ownerAuth) + .header("X-Amz-Target", "AmazonSSM.CreateDocument") + .contentType(SSM_CONTENT_TYPE) + .body(""" + { + "Name": "Owner-Only-Document", + "DocumentType": "Session", + "Content": "{\\"schemaVersion\\":\\"1.0\\"}" + } + """) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .header("Authorization", otherAuth) + .header("X-Amz-Target", "AmazonSSM.ModifyDocumentPermission") + .contentType(SSM_CONTENT_TYPE) + .body(""" + { + "Name": "Owner-Only-Document", + "PermissionType": "Share", + "AccountIdsToAdd": ["444444444444"] + } + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidDocument")); + + // …and the owner's own share state is untouched. + given() + .header("Authorization", ownerAuth) + .header("X-Amz-Target", "AmazonSSM.DescribeDocumentPermission") + .contentType(SSM_CONTENT_TYPE) + .body(""" + { + "Name": "Owner-Only-Document", + "PermissionType": "Share" + } + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("AccountIds", not(hasItem("444444444444"))); + } + + // ── DocumentType (botocore: enum, 17 values) ── + + @Test + void createDocument_rejectsAnUnmodelledDocumentType() { + given() + .header("X-Amz-Target", "AmazonSSM.CreateDocument") + .contentType(SSM_CONTENT_TYPE) + .body(""" + { + "Name": "Bad-Document-Type", + "DocumentType": "NotADocumentType", + "Content": "{\\"schemaVersion\\":\\"1.0\\"}" + } + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")); + + // The rejected document must not have been stored. + given() + .header("X-Amz-Target", "AmazonSSM.GetDocument") + .contentType(SSM_CONTENT_TYPE) + .body(""" + { "Name": "Bad-Document-Type" } + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidDocument")); + } + + @Test + void createDocument_acceptsEveryModelledDocumentType() { + String[] documentTypes = { + "Command", "Policy", "Automation", "Session", "Package", + "ApplicationConfiguration", "ApplicationConfigurationSchema", "DeploymentStrategy", + "ChangeCalendar", "Automation.ChangeTemplate", "ProblemAnalysis", + "ProblemAnalysisTemplate", "CloudFormation", "ConformancePackTemplate", + "QuickSetup", "ManualApprovalPolicy", "AutoApprovalPolicy"}; + for (int i = 0; i < documentTypes.length; i++) { + given() + .header("X-Amz-Target", "AmazonSSM.CreateDocument") + .contentType(SSM_CONTENT_TYPE) + .body(""" + { + "Name": "Modelled-Type-%d", + "DocumentType": "%s", + "Content": "{\\"schemaVersion\\":\\"1.0\\",\\"n\\":%d}" + } + """.formatted(i, documentTypes[i], i)) + .when() + .post("/") + .then() + .statusCode(200) + .body("DocumentDescription.DocumentType", equalTo(documentTypes[i])); + } + } + + // ── AccountIdsToAdd/Remove (botocore: list max 20, member (?i)all|[0-9]{12}) ── + + @Test + void modifyDocumentPermission_rejectsAnAccountIdThatIsNotAnAccountId() { + createSharableDocument("Bad-Account-Id-Document"); + + given() + .header("X-Amz-Target", "AmazonSSM.ModifyDocumentPermission") + .contentType(SSM_CONTENT_TYPE) + .body(""" + { + "Name": "Bad-Account-Id-Document", + "PermissionType": "Share", + "AccountIdsToAdd": ["not-an-account"] + } + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")); + + // Nothing may have been shared. + given() + .header("X-Amz-Target", "AmazonSSM.DescribeDocumentPermission") + .contentType(SSM_CONTENT_TYPE) + .body(""" + { "Name": "Bad-Account-Id-Document", "PermissionType": "Share" } + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("AccountIds", not(hasItem("not-an-account"))); + } + + /** The model spells the wildcard {@code (?i)all}, so "all" and "All" are both account ids. */ + @Test + void modifyDocumentPermission_acceptsTheAllWildcard() { + createSharableDocument("All-Wildcard-Document"); + + given() + .header("X-Amz-Target", "AmazonSSM.ModifyDocumentPermission") + .contentType(SSM_CONTENT_TYPE) + .body(""" + { + "Name": "All-Wildcard-Document", + "PermissionType": "Share", + "AccountIdsToAdd": ["All"] + } + """) + .when() + .post("/") + .then() + .statusCode(200); + } + + @Test + void modifyDocumentPermission_rejectsMoreThanTwentyAccountIds() { + createSharableDocument("Too-Many-Accounts-Document"); + + StringBuilder ids = new StringBuilder(); + for (int i = 0; i < 21; i++) { + ids.append(i == 0 ? "" : ",").append("\"%012d\"".formatted(100000000000L + i)); + } + + given() + .header("X-Amz-Target", "AmazonSSM.ModifyDocumentPermission") + .contentType(SSM_CONTENT_TYPE) + .body(""" + { + "Name": "Too-Many-Accounts-Document", + "PermissionType": "Share", + "AccountIdsToAdd": [%s] + } + """.formatted(ids)) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")); + } + + private static void createSharableDocument(String name) { + given() + .header("X-Amz-Target", "AmazonSSM.CreateDocument") + .contentType(SSM_CONTENT_TYPE) + .body(""" + { + "Name": "%s", + "DocumentType": "Session", + "Content": "{\\"schemaVersion\\":\\"1.0\\",\\"doc\\":\\"%s\\"}" + } + """.formatted(name, name)) + .when() + .post("/") + .then() + .statusCode(200); + } } 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.java index fa536890bc..2d338e0d7a 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 @@ -1,13 +1,26 @@ package io.github.hectorvent.floci.services.ssm; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.InMemoryStorage; +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.SsmDocument; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.function.Predicate; import static org.junit.jupiter.api.Assertions.*; @@ -18,12 +31,63 @@ class SsmServiceTest { @BeforeEach void setUp() { ssmService = new SsmService( + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), 5 ); } + @Test + void describeDocumentPermissionEmptyByDefault() { + ssmService.createDocument("MyDoc", "{}", "Command", "us-east-1"); + List accountIds = ssmService.describeDocumentPermission("MyDoc", "us-east-1"); + assertTrue(accountIds.isEmpty()); + } + + @Test + void describeDocumentPermissionUnknownDocumentThrowsInvalidDocument() { + AwsException ex = assertThrows(AwsException.class, () -> + ssmService.describeDocumentPermission("NoSuchDoc", "us-east-1")); + assertEquals("InvalidDocument", ex.getErrorCode()); + } + + @Test + void modifyDocumentPermissionUnknownDocumentThrowsInvalidDocument() { + AwsException ex = assertThrows(AwsException.class, () -> + ssmService.modifyDocumentPermission("NoSuchDoc", + List.of("111111111111"), List.of(), "us-east-1")); + assertEquals("InvalidDocument", ex.getErrorCode()); + } + + @Test + void modifyDocumentPermissionAddsAndRemovesAccounts() { + String region = "us-east-1"; + ssmService.createDocument("ShareDoc", "{}", "Command", region); + ssmService.modifyDocumentPermission("ShareDoc", + List.of("111111111111", "222222222222"), List.of(), region); + assertEquals(List.of("111111111111", "222222222222"), + ssmService.describeDocumentPermission("ShareDoc", region)); + + ssmService.modifyDocumentPermission("ShareDoc", + List.of(), List.of("111111111111"), region); + assertEquals(List.of("222222222222"), + ssmService.describeDocumentPermission("ShareDoc", region)); + } + + @Test + void modifyDocumentPermissionIsIdempotentAndRegionScoped() { + String region = "us-east-1"; + ssmService.createDocument("Doc", "{}", "Command", region); + ssmService.modifyDocumentPermission("Doc", List.of("333333333333"), List.of(), region); + ssmService.modifyDocumentPermission("Doc", List.of("333333333333"), List.of(), region); + assertEquals(List.of("333333333333"), ssmService.describeDocumentPermission("Doc", region)); + // The document itself is region-scoped, so the other region has no document to describe. + AwsException ex = assertThrows(AwsException.class, () -> + ssmService.describeDocumentPermission("Doc", "eu-west-1")); + assertEquals("InvalidDocument", ex.getErrorCode()); + } + @Test void putAndGetParameter() { String region = "eu-west-1"; @@ -146,4 +210,248 @@ class SsmServiceTest { assertEquals("v3", history.get(0).getValue()); assertEquals("v7", history.get(4).getValue()); } + + @Test + void getDocumentUnknownThrowsInvalidDocument() { + // The AWS SDK maps this code to its InvalidDocument exception class; + // LZA's session-manager-settings Lambda branches on it to create the doc. + AwsException ex = assertThrows(AwsException.class, () -> + ssmService.getDocument("SSM-SessionManagerRunShell", "us-east-1")); + assertEquals("InvalidDocument", ex.getErrorCode()); + } + + @Test + void createAndGetDocument() { + String region = "us-east-1"; + String content = "{\"schemaVersion\":\"1.0\",\"inputs\":{\"runAsEnabled\":false}}"; + ssmService.createDocument("SSM-SessionManagerRunShell", content, "Session", region); + + SsmDocument doc = ssmService.getDocument("SSM-SessionManagerRunShell", region); + assertEquals("SSM-SessionManagerRunShell", doc.getName()); + assertEquals(content, doc.getContent()); + assertEquals("Session", doc.getDocumentType()); + assertEquals(1, doc.getDocumentVersion()); + assertEquals("Active", doc.getStatus()); + } + + @Test + void createDocumentTwiceThrowsAlreadyExists() { + String region = "us-east-1"; + ssmService.createDocument("Doc", "{}", "Command", region); + AwsException ex = assertThrows(AwsException.class, () -> + ssmService.createDocument("Doc", "{}", "Command", region)); + assertEquals("DocumentAlreadyExists", ex.getErrorCode()); + } + + @Test + void updateDocumentBumpsVersion() { + String region = "us-east-1"; + ssmService.createDocument("Doc", "{\"a\":1}", "Session", region); + + SsmDocument updated = ssmService.updateDocument("Doc", "{\"a\":2}", region); + assertEquals(2, updated.getDocumentVersion()); + assertEquals("{\"a\":2}", ssmService.getDocument("Doc", region).getContent()); + } + + @Test + void updateDocumentSameContentThrowsDuplicateDocumentContent() { + String region = "us-east-1"; + ssmService.createDocument("Doc", "{\"a\":1}", "Session", region); + AwsException ex = assertThrows(AwsException.class, () -> + ssmService.updateDocument("Doc", "{\"a\":1}", region)); + assertEquals("DuplicateDocumentContent", ex.getErrorCode()); + } + + @Test + void updateDocumentUnknownThrowsInvalidDocument() { + AwsException ex = assertThrows(AwsException.class, () -> + ssmService.updateDocument("Missing", "{}", "us-east-1")); + assertEquals("InvalidDocument", ex.getErrorCode()); + } + + @Test + void documentsAreRegionScoped() { + ssmService.createDocument("Doc", "{}", "Session", "us-east-1"); + AwsException ex = assertThrows(AwsException.class, () -> + ssmService.getDocument("Doc", "eu-west-1")); + assertEquals("InvalidDocument", ex.getErrorCode()); + } + + // ── Service settings (LZA ssm-block-public-document-sharing) ── + + private static final String PUBLIC_SHARING = "/ssm/documents/console/public-sharing-permission"; + + @Test + void getServiceSettingReturnsDefaultWhenNeverCustomized() { + ServiceSetting setting = ssmService.getServiceSetting(PUBLIC_SHARING, "us-east-1"); + + assertEquals(PUBLIC_SHARING, setting.getSettingId()); + assertEquals("Enable", setting.getSettingValue()); + assertEquals("Default", setting.getStatus()); + assertEquals("arn:aws:ssm:us-east-1:000000000000:servicesetting" + PUBLIC_SHARING, + setting.getArn()); + assertNotNull(setting.getLastModifiedDate()); + assertNotNull(setting.getLastModifiedUser()); + } + + @Test + void updateServiceSettingCustomizesValueAndStatus() { + ssmService.updateServiceSetting(PUBLIC_SHARING, "Disable", "us-east-1"); + ServiceSetting setting = ssmService.getServiceSetting(PUBLIC_SHARING, "us-east-1"); + + assertEquals("Disable", setting.getSettingValue()); + assertEquals("Customized", setting.getStatus()); + assertNotNull(setting.getLastModifiedDate()); + } + + @Test + void resetServiceSettingRestoresDefault() { + ssmService.updateServiceSetting(PUBLIC_SHARING, "Disable", "us-east-1"); + ServiceSetting reset = ssmService.resetServiceSetting(PUBLIC_SHARING, "us-east-1"); + assertEquals("Enable", reset.getSettingValue()); + + ServiceSetting after = ssmService.getServiceSetting(PUBLIC_SHARING, "us-east-1"); + assertEquals("Enable", after.getSettingValue()); + assertEquals("Default", after.getStatus()); + } + + @Test + void unknownServiceSettingThrows() { + AwsException ex = assertThrows(AwsException.class, () -> + ssmService.getServiceSetting("/ssm/bogus/does-not-exist", "us-east-1")); + assertEquals("ServiceSettingNotFound", ex.getErrorCode()); + } + + @Test + void updateUnknownServiceSettingThrows() { + AwsException ex = assertThrows(AwsException.class, () -> + ssmService.updateServiceSetting("/ssm/bogus/does-not-exist", "x", "us-east-1")); + assertEquals("ServiceSettingNotFound", ex.getErrorCode()); + } + + @Test + void serviceSettingsAreRegionScoped() { + ssmService.updateServiceSetting(PUBLIC_SHARING, "Disable", "us-east-1"); + + ServiceSetting other = ssmService.getServiceSetting(PUBLIC_SHARING, "eu-west-1"); + assertEquals("Enable", other.getSettingValue()); + assertEquals("Default", other.getStatus()); + } + + @Test + void serviceSettingsAreAccountScoped() { + // LZA assumes a role into each member account and updates the setting + // there; a shared store must still keep per-account values separate. + InMemoryStorage sharedSettings = new InMemoryStorage<>(); + SsmService accountA = new SsmService(new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>(), + sharedSettings, 5, new RegionResolver("us-east-1", "111111111111")); + SsmService accountB = new SsmService(new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>(), + sharedSettings, 5, new RegionResolver("us-east-1", "222222222222")); + + accountA.updateServiceSetting(PUBLIC_SHARING, "Disable", "us-east-1"); + + assertEquals("Disable", accountA.getServiceSetting(PUBLIC_SHARING, "us-east-1").getSettingValue()); + ServiceSetting b = accountB.getServiceSetting(PUBLIC_SHARING, "us-east-1"); + assertEquals("Enable", b.getSettingValue()); + assertEquals("arn:aws:ssm:us-east-1:222222222222:servicesetting" + PUBLIC_SHARING, b.getArn()); + } + + /** + * A delete that overlaps a same-name recreate-and-share must not let the delete's + * trailing permission cleanup wipe out the recreated document's new shares. + * {@code documentStore.delete} is instrumented to signal once it starts and then + * block, giving a concurrent createDocument/modifyDocumentPermission call a window + * to run before deleteDocument reaches documentPermissionStore.delete. + */ + @Test + void deleteOverlappingRecreateAndShareDoesNotLoseNewPermission() throws Exception { + String region = "us-east-1"; + String name = "RaceDoc"; + + CountDownLatch deleteStarted = new CountDownLatch(1); + CountDownLatch releaseDelete = new CountDownLatch(1); + InMemoryStorage realDocumentStore = new InMemoryStorage<>(); + StorageBackend instrumentedDocumentStore = + new StorageBackend<>() { + @Override + public void put(String key, SsmDocument value) { + realDocumentStore.put(key, value); + } + + @Override + public Optional get(String key) { + return realDocumentStore.get(key); + } + + @Override + public void delete(String key) { + realDocumentStore.delete(key); + deleteStarted.countDown(); + try { + releaseDelete.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + @Override + public List scan(Predicate keyFilter) { + return realDocumentStore.scan(keyFilter); + } + + @Override + public Set keys() { + return realDocumentStore.keys(); + } + + @Override + public void flush() { + realDocumentStore.flush(); + } + + @Override + public void load() { + realDocumentStore.load(); + } + + @Override + public void clear() { + realDocumentStore.clear(); + } + }; + + SsmService service = new SsmService(new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), instrumentedDocumentStore, + new InMemoryStorage<>(), 5, new RegionResolver(region, "000000000000")); + service.createDocument(name, "{}", "Command", region); + service.modifyDocumentPermission(name, List.of("111111111111"), List.of(), region); + + ExecutorService pool = Executors.newFixedThreadPool(2); + try { + Future deleteFuture = pool.submit(() -> service.deleteDocument(name, region)); + assertTrue(deleteStarted.await(10, TimeUnit.SECONDS), + "delete must finish removing the document before this window opens"); + + Future recreateFuture = pool.submit(() -> { + service.createDocument(name, "{}", "Command", region); + service.modifyDocumentPermission(name, List.of("222222222222"), List.of(), region); + return null; + }); + assertThrows(TimeoutException.class, () -> recreateFuture.get(300, TimeUnit.MILLISECONDS), + "recreate-and-share must be serialized against the in-flight delete, " + + "not interleaved with it"); + + releaseDelete.countDown(); + deleteFuture.get(10, TimeUnit.SECONDS); + recreateFuture.get(10, TimeUnit.SECONDS); + } finally { + pool.shutdownNow(); + } + + assertEquals(List.of("222222222222"), service.describeDocumentPermission(name, region), + "the delete's trailing permission cleanup must not remove the recreated " + + "document's new share"); + } }