feat(ssm): model documents and associations with full lifecycle operations (#3057)

* feat(ssm): model SsmAssociation and extend SsmDocument metadata

* feat(ssm): add listDocuments and association lifecycle methods to SsmService

* feat(ssm): handle ListDocuments and Association actions in SsmJsonHandler

* test(ssm): add integration tests for ListDocuments and Association lifecycle

* test(ssm): update listDocuments_returnsEmptyList in SsmIntegrationTest to use filter

* fix(ssm): AWS fidelity fixes for associations and document listing

- reject duplicate CreateAssociation calls (name+instanceId or
  name+targets) with AssociationAlreadyExists
- implement UpdateAssociation end-to-end with an AssociationVersion
  counter
- read MaxErrors/MaxConcurrency/ComplianceSeverity on create instead
  of silently dropping them
- honor ListAssociations (AssociationFilterList) and ListDocuments
  (Owner) filters instead of ignoring them
- set SsmDocument.owner on create so ListDocuments/Owner filtering
  works
- remove the invented GetAssociation action (real SSM only has
  DescribeAssociation)
- require InstanceId or Targets on CreateAssociation
- fix a startsWith("") bug that let a blank Name filter value match
  every document

Also: extract targetsToArray/parseTargets/parseParameters helpers,
drop dead SsmAssociation.getDate()/setDate(), and de-flake/rename two
ListDocuments/ListAssociations tests that no longer describe
unmodeled resources.

* fix(ssm): address PR #3057 review comments

- honor the ListDocuments PlatformTypes filter instead of ignoring it
- validate DocumentVersion on CreateAssociation/UpdateAssociation so
  associations can't persist a reference to a document version that
  never existed
- treat a legacy null-owner document (persisted before Owner existed)
  as owned by the caller's account when filtering by Owner, since the
  store already guarantees it belongs to that account

* fix(ssm): retain document version history and normalize legacy owners

- retain version history in SsmDocument on updateDocument so associations and getDocument can resolve historical versions
- validate DocumentVersion against document's retained version history
- normalize null legacy document owners to caller account ID so Owner is included in ListDocuments responses

* fix(ssm): resolve legacy document versions that predate retained history

A document persisted before the Versions field was added deserializes
with an empty versions map even when its DocumentVersion is already
past 1, since only the current content was ever retained. Both
validateDocumentVersion and the GetDocument/DescribeDocument version
lookups required exact map membership, so a legitimate historical
version number for such a document was rejected with
InvalidDocumentVersion instead of resolving to a best-effort fallback.

SsmDocument.hasVersion/getContentForVersion now treat any numeric
version in 1..documentVersion as valid, falling back to the current
content when the original was never captured.

* fix(ssm): stop GetDocument/DescribeDocument from mislabeling content

hasVersion's lenient range check (added to stop legitimate legacy
version references being rejected on association create/update) was
also used by GetDocument/DescribeDocument's version lookup, together
with a content fallback to the document's current content. That
meant a request for an old version whose real content was never
retained got back the current content labeled as the requested
version -- a caller had no way to tell it wasn't genuine history.

Split the concern: hasVersion stays lenient for reference checks that
never expose content (association DocumentVersion validation).
GetDocument/DescribeDocument now use the new hasRetainedContent,
which only accepts versions actually present in the retained map, and
getContentForVersion no longer fabricates a fallback.

* docs(ssm): document the hasVersion/hasRetainedContent divergence

A review comment on PR #3057 flagged that an association can
reference a legacy document version successfully (hasVersion) while
GetDocument/DescribeDocument reject the same version
(hasRetainedContent) because its content was never captured.

Not fixing this: the two prior fixes on this thread already ruled out
both alternatives -- rejecting the association reference reintroduces
the original bug (legitimate legacy versions blocked), and returning
fallback content in GetDocument reintroduces the mislabeled-content
bug. The divergence is the least-bad option given the content is
genuinely unrecoverable. Documented the reasoning on both methods and
in the regression test so it isn't "fixed" back into either bug.
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-09-05 10:28:04 -04:00
1 parent 6653b9a4e4
commit f00fb4c289
8 files changed
+2076 -23

No files matched your search

@@ -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 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);
// 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());
@@ -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.
@@ -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;
}
}
}
@@ -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);
}
}