Skip to content

armgit / floci

Public Imported from GitHub
0

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

fix(ssm): support parameter selectors in GetParameter and align LabelParameterVersion with AWS (#4461)

Vũ Thế Huy5ae46c2bd31a
diff --git a/docs/services/ssm.md b/docs/services/ssm.md
index 01fc36336d..1410110507 100644
--- a/docs/services/ssm.md
+++ b/docs/services/ssm.md
@@ -10,8 +10,8 @@
| Action | Description |
|---|---|
| `PutParameter` | Create or update a parameter |
-| `GetParameter` | Get a single parameter by name |
-| `GetParameters` | Get multiple parameters by name |
+| `GetParameter` | Get a single parameter by name, optionally `name:version` or `name:label` |
+| `GetParameters` | Get multiple parameters by name, with the same `name:version` and `name:label` selectors |
| `GetParametersByPath` | Get all parameters under a path prefix |
| `DeleteParameter` | Delete a parameter |
| `DeleteParameters` | Delete multiple parameters |
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 f561dc892e..8f2720b661 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
@@ -149,7 +149,7 @@ public class SsmJsonHandler {
}
response.set("Parameters", parametersArray);
response.set("InvalidParameters", invalidParameterNames(names,
- params.stream().map(Parameter::getName).toList()));
+ params.stream().map(p -> p.getName() + (p.getSelector() == null ? "" : p.getSelector())).toList()));
return Response.ok(response).build();
}
@@ -929,17 +929,61 @@ public class SsmJsonHandler {
return Response.ok(response).build();
}
+ private static final int MAX_LABELS = 10;
+ private static final int MAX_LABEL_LENGTH = 100;
+
+ private List<String> requireLabels(JsonNode request) {
+ JsonNode labelsNode = request.path("Labels");
+ if (labelsNode.isMissingNode() || labelsNode.isNull()) {
+ throw new AwsException("ValidationException",
+ "1 validation error detected: Value null at 'labels' failed to satisfy constraint: Member must not be null",
+ 400);
+ }
+ if (!labelsNode.isArray() || labelsNode.isEmpty()) {
+ throw new AwsException("ValidationException",
+ "1 validation error detected: Value at 'labels' failed to satisfy constraint: Member must have length greater than or equal to 1",
+ 400);
+ }
+ if (labelsNode.size() > MAX_LABELS) {
+ throw new AwsException("ValidationException",
+ "1 validation error detected: Value at 'labels' failed to satisfy constraint: Member must have length less than or equal to "
+ + MAX_LABELS,
+ 400);
+ }
+ List<String> labels = new ArrayList<>(labelsNode.size());
+ for (JsonNode l : labelsNode) {
+ String label = l.asText();
+ if (!l.isTextual() || label.isEmpty()) {
+ throw new AwsException("ValidationException",
+ "1 validation error detected: Value at 'labels' failed to satisfy constraint: Member must have length greater than or equal to 1",
+ 400);
+ }
+ if (label.length() > MAX_LABEL_LENGTH) {
+ throw new AwsException("ValidationException",
+ "1 validation error detected: Value at 'labels' failed to satisfy constraint: Member must have length less than or equal to "
+ + MAX_LABEL_LENGTH,
+ 400);
+ }
+ labels.add(label);
+ }
+ return labels;
+ }
+
private Response handleLabelParameterVersion(JsonNode request, String region) {
String name = request.path("Name").asText();
- long parameterVersion = request.path("ParameterVersion").asLong();
- List<String> labels = new ArrayList<>();
- request.path("Labels").forEach(l -> labels.add(l.asText()));
+ Long parameterVersion = request.hasNonNull("ParameterVersion")
+ ? request.path("ParameterVersion").asLong()
+ : null;
+ List<String> labels = requireLabels(request);
- ssmService.labelParameterVersion(name, parameterVersion, labels, region);
+ SsmService.LabelParameterVersionResult result = ssmService.labelParameterVersion(
+ name, parameterVersion, labels, region);
ObjectNode response = objectMapper.createObjectNode();
- response.set("InvalidLabels", objectMapper.createArrayNode());
- response.put("ParameterVersion", parameterVersion);
+ ArrayNode invalidArray = objectMapper.createArrayNode();
+ result.invalidLabels().forEach(invalidArray::add);
+ response.set("InvalidLabels", invalidArray);
+ response.put("ParameterVersion", result.parameterVersion());
return Response.ok(response).build();
}
@@ -987,6 +1031,9 @@ public class SsmJsonHandler {
node.put("LastModifiedDate", p.getLastModifiedDate().toEpochMilli() / 1000.0);
node.put("ARN", p.getArn());
node.put("DataType", p.getDataType());
+ if (p.getSelector() != null) {
+ node.put("Selector", p.getSelector());
+ }
return node;
}
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 ad4a5219d3..66d284cb77 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
@@ -205,9 +205,16 @@ public class SsmService implements ResourceProvider {
}
public Parameter getParameter(String name, String region) {
- return findParameter(name, region)
- .orElseThrow(() -> new AwsException("ParameterNotFound",
- "Parameter " + name + " not found.", 400));
+ return findParameter(name, region).orElseThrow(() -> {
+ int separator = name == null ? -1 : name.lastIndexOf(':');
+ if (separator > 0 && separator < name.length() - 1
+ && parameterStore.get(regionKey(region, name.substring(0, separator))).isPresent()) {
+ return new AwsException("ParameterVersionNotFound",
+ "Systems Manager could not find version or label " + name.substring(separator + 1)
+ + " of " + name.substring(0, separator) + ". Verify the version and try again.", 400);
+ }
+ return new AwsException("ParameterNotFound", "Parameter " + name + " not found.", 400);
+ });
}
public List<Parameter> getParameters(List<String> names, String region) {
@@ -243,9 +250,50 @@ public class SsmService implements ResourceProvider {
if (stored.isPresent()) {
return stored;
}
+ Optional<Parameter> selected = findSelectedVersion(name, region);
+ if (selected.isPresent()) {
+ return selected;
+ }
return publicParameter(name, region);
}
+ /**
+ * A read may name a version or label as {@code name:version} or {@code name:label}. A
+ * parameter name cannot contain a colon, so the last one always starts the selector. The
+ * answer is a copy built from the history entry: it carries the base name and the selector
+ * as AWS returns them, and nothing is written back.
+ */
+ private Optional<Parameter> findSelectedVersion(String name, String region) {
+ int separator = name == null ? -1 : name.lastIndexOf(':');
+ if (separator <= 0 || separator == name.length() - 1) {
+ return Optional.empty();
+ }
+ String baseName = name.substring(0, separator);
+ String selector = name.substring(separator + 1);
+ String storageKey = regionKey(region, baseName);
+ Optional<Parameter> current = parameterStore.get(storageKey);
+ if (current.isEmpty()) {
+ return Optional.empty();
+ }
+ boolean isVersion = selector.chars().allMatch(Character::isDigit);
+ // A label is unique across parameter versions because attaching it moves it from any prior version.
+ return historyStore.get(storageKey).orElse(List.of()).stream()
+ .filter(h -> isVersion
+ ? String.valueOf(h.getVersion()).equals(selector)
+ : h.getLabels() != null && h.getLabels().contains(selector))
+ .max(Comparator.comparingLong(ParameterHistory::getVersion))
+ .map(h -> {
+ Parameter parameter = new Parameter(baseName, h.getValue(), h.getType());
+ parameter.setVersion(h.getVersion());
+ parameter.setDescription(h.getDescription());
+ parameter.setLastModifiedDate(h.getLastModifiedDate());
+ parameter.setArn(current.get().getArn());
+ parameter.setDataType(current.get().getDataType());
+ parameter.setSelector(":" + selector);
+ return parameter;
+ });
+ }
+
/**
* AWS publishes read-only AMI id parameters under {@code /aws/service/} in every account
* with no setup, so a read of one of those names is answered from the EC2 image catalog.
@@ -408,39 +456,134 @@ public class SsmService implements ResourceProvider {
});
}
- public void labelParameterVersion(String name, long parameterVersion, List<String> labels, String region) {
- String storageKey = regionKey(region, name);
- if (parameterStore.get(storageKey).isEmpty()) {
- throw new AwsException("ParameterNotFound",
- "Parameter " + name + " not found.", 400);
+ public record LabelParameterVersionResult(long parameterVersion, List<String> invalidLabels) {}
+
+ public synchronized LabelParameterVersionResult labelParameterVersion(String name, Long parameterVersion,
+ List<String> labels, String region) {
+ if (labels == null || labels.isEmpty()) {
+ throw new AwsException("ValidationException",
+ "1 validation error detected: Value at 'labels' failed to satisfy constraint: Member must have length greater than or equal to 1",
+ 400);
+ }
+ if (labels.size() > 10) {
+ throw new AwsException("ValidationException",
+ "1 validation error detected: Value at 'labels' failed to satisfy constraint: Member must have length less than or equal to 10",
+ 400);
+ }
+ for (String label : labels) {
+ if (label == null || label.isEmpty()) {
+ throw new AwsException("ValidationException",
+ "1 validation error detected: Value at 'labels' failed to satisfy constraint: Member must have length greater than or equal to 1",
+ 400);
+ }
+ if (label.length() > 100) {
+ throw new AwsException("ValidationException",
+ "1 validation error detected: Value at 'labels' failed to satisfy constraint: Member must have length less than or equal to 100",
+ 400);
+ }
}
- List<ParameterHistory> history = historyStore.get(storageKey)
- .orElse(List.of());
+ String storageKey = regionKey(region, name);
+ Parameter current = parameterStore.get(storageKey).orElseThrow(() ->
+ new AwsException("ParameterNotFound", "Parameter " + name + " not found.", 400));
- history = new ArrayList<>(history);
+ long targetVersion = parameterVersion == null
+ ? current.getVersion()
+ : parameterVersion;
+
+ List<ParameterHistory> existingHistory = historyStore.get(storageKey).orElse(List.of());
+ List<ParameterHistory> updatedHistory = new ArrayList<>(existingHistory.size());
- boolean found = false;
- for (ParameterHistory h : history) {
- if (h.getVersion() == parameterVersion) {
- List<String> existing = h.getLabels() != null ? new ArrayList<>(h.getLabels()) : new ArrayList<>();
- for (String label : labels) {
- if (!existing.contains(label)) {
- existing.add(label);
+ ParameterHistory targetCopy = null;
+ for (ParameterHistory h : existingHistory) {
+ ParameterHistory copy = new ParameterHistory(h);
+ if (copy.getVersion() == targetVersion) {
+ targetCopy = copy;
+ }
+ updatedHistory.add(copy);
+ }
+
+ if (targetCopy == null) {
+ throw new AwsException("ParameterVersionNotFound",
+ "Parameter version " + targetVersion + " not found.", 400);
+ }
+
+ List<String> invalidLabels = new ArrayList<>();
+ List<String> validLabels = new ArrayList<>();
+ if (labels != null) {
+ for (String label : labels) {
+ if (isValidLabel(label)) {
+ if (!validLabels.contains(label)) {
+ validLabels.add(label);
+ }
+ } else {
+ if (!invalidLabels.contains(label)) {
+ invalidLabels.add(label);
}
}
- h.setLabels(existing);
- found = true;
- break;
}
}
- if (!found) {
- throw new AwsException("ParameterVersionNotFound", "Parameter version " + parameterVersion + " not found.", 400);
+ List<String> targetLabels = targetCopy.getLabels() != null
+ ? new ArrayList<>(targetCopy.getLabels())
+ : new ArrayList<>();
+
+ int newLabelCount = targetLabels.size();
+ for (String validLabel : validLabels) {
+ if (!targetLabels.contains(validLabel)) {
+ newLabelCount++;
+ }
+ }
+ if (newLabelCount > 10) {
+ throw new AwsException("ParameterVersionLabelLimitExceeded",
+ "The parameter version already has the maximum number of labels (10).", 400);
}
- historyStore.put(storageKey, history);
- LOG.infov("Labeled parameter {0} version {1} with labels {2}", name, parameterVersion, labels);
+ for (ParameterHistory h : updatedHistory) {
+ if (h.getVersion() != targetVersion && h.getLabels() != null) {
+ List<String> otherLabels = new ArrayList<>(h.getLabels());
+ if (otherLabels.removeAll(validLabels)) {
+ h.setLabels(otherLabels);
+ }
+ }
+ }
+
+ for (String validLabel : validLabels) {
+ if (!targetLabels.contains(validLabel)) {
+ targetLabels.add(validLabel);
+ }
+ }
+ targetCopy.setLabels(targetLabels);
+
+ historyStore.put(storageKey, updatedHistory);
+ LOG.infov("Labeled parameter {0} version {1} with labels {2}", name, targetVersion, validLabels);
+ return new LabelParameterVersionResult(targetVersion, invalidLabels);
+ }
+
+ public synchronized LabelParameterVersionResult labelParameterVersion(String name, long parameterVersion,
+ List<String> labels, String region) {
+ return labelParameterVersion(name, Long.valueOf(parameterVersion), labels, region);
+ }
+
+ private static boolean isValidLabel(String label) {
+ if (label == null || label.isEmpty() || label.length() > 100) {
+ return false;
+ }
+ if (Character.isDigit(label.charAt(0))) {
+ return false;
+ }
+ String lower = label.toLowerCase(Locale.ROOT);
+ if (lower.startsWith("aws") || lower.startsWith("ssm")) {
+ return false;
+ }
+ for (int i = 0; i < label.length(); i++) {
+ char c = label.charAt(i);
+ if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')
+ || c == '.' || c == '-' || c == '_')) {
+ return false;
+ }
+ }
+ return true;
}
public void addTagsToResource(String resourceId, Map<String, String> tags, String region) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/ssm/model/Parameter.java b/src/main/java/io/github/hectorvent/floci/services/ssm/model/Parameter.java
index 136b1bfcda..37159d6da2 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ssm/model/Parameter.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ssm/model/Parameter.java
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.ssm.model;
import com.fasterxml.jackson.annotation.JsonAlias;
+import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.quarkus.runtime.annotations.RegisterForReflection;
@@ -41,6 +42,10 @@ public class Parameter {
@JsonAlias({"tags", "Tags"})
private Map<String, String> tags = new HashMap<>();
+ // Only set on a copy answering a name:version or name:label read; never persisted.
+ @JsonIgnore
+ private String selector;
+
public Parameter() {}
public Parameter(String name, String value, String type) {
@@ -77,4 +82,7 @@ public class Parameter {
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags; }
+
+ public String getSelector() { return selector; }
+ public void setSelector(String selector) { this.selector = selector; }
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ssm/model/ParameterHistory.java b/src/main/java/io/github/hectorvent/floci/services/ssm/model/ParameterHistory.java
index 42a5ab4a23..2e77fe13d8 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ssm/model/ParameterHistory.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ssm/model/ParameterHistory.java
@@ -44,6 +44,16 @@ public class ParameterHistory {
this.description = parameter.getDescription();
}
+ public ParameterHistory(ParameterHistory other) {
+ this.name = other.name;
+ this.version = other.version;
+ this.value = other.value;
+ this.type = other.type;
+ this.lastModifiedDate = other.lastModifiedDate;
+ this.description = other.description;
+ this.labels = other.labels != null ? new ArrayList<>(other.labels) : new ArrayList<>();
+ }
+
public String getName() { return name; }
public void setName(String name) { this.name = name; }
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 881190c5b3..8660d04ea6 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
@@ -1624,6 +1624,153 @@ class SsmIntegrationTest {
.statusCode(200);
}
+ @Test
+ void getParameterWithVersionAndLabelSelectors() {
+ for (String value : new String[] {"key1", "key2"}) {
+ given()
+ .header("X-Amz-Target", "AmazonSSM.PutParameter")
+ .contentType(SSM_CONTENT_TYPE)
+ .body("""
+ { "Name": "/selector/param", "Value": "%s", "Type": "SecureString", "Overwrite": true }
+ """.formatted(value))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+ given()
+ .header("X-Amz-Target", "AmazonSSM.LabelParameterVersion")
+ .contentType(SSM_CONTENT_TYPE)
+ .body("""
+ { "Name": "/selector/param", "ParameterVersion": 1, "Labels": ["previous", "2", "aws:reserved"] }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("ParameterVersion", equalTo(1))
+ .body("InvalidLabels", containsInAnyOrder("2", "aws:reserved"));
+
+ given()
+ .header("X-Amz-Target", "AmazonSSM.GetParameter")
+ .contentType(SSM_CONTENT_TYPE)
+ .body("""
+ { "Name": "/selector/param:1", "WithDecryption": true }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("Parameter.Name", equalTo("/selector/param"))
+ .body("Parameter.Selector", equalTo(":1"))
+ .body("Parameter.Value", equalTo("key1"))
+ .body("Parameter.Version", equalTo(1));
+
+ given()
+ .header("X-Amz-Target", "AmazonSSM.GetParameter")
+ .contentType(SSM_CONTENT_TYPE)
+ .body("""
+ { "Name": "/selector/param:2", "WithDecryption": true }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("Parameter.Name", equalTo("/selector/param"))
+ .body("Parameter.Selector", equalTo(":2"))
+ .body("Parameter.Value", equalTo("key2"))
+ .body("Parameter.Version", equalTo(2));
+
+ given()
+ .header("X-Amz-Target", "AmazonSSM.GetParameter")
+ .contentType(SSM_CONTENT_TYPE)
+ .body("""
+ { "Name": "/selector/param:previous" }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("Parameter.Selector", equalTo(":previous"))
+ .body("Parameter.Version", equalTo(1));
+
+ given()
+ .header("X-Amz-Target", "AmazonSSM.GetParameter")
+ .contentType(SSM_CONTENT_TYPE)
+ .body("""
+ { "Name": "/selector/param:9" }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("ParameterVersionNotFound"));
+
+ given()
+ .header("X-Amz-Target", "AmazonSSM.GetParameters")
+ .contentType(SSM_CONTENT_TYPE)
+ .body("""
+ { "Names": ["/selector/param:1", "/selector/param:9"] }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("Parameters.Value", contains("key1"))
+ .body("InvalidParameters", contains("/selector/param:9"));
+ }
+
+ @Test
+ void labelParameterVersion_validationErrors() {
+ given()
+ .header("X-Amz-Target", "AmazonSSM.LabelParameterVersion")
+ .contentType(SSM_CONTENT_TYPE)
+ .body("""
+ { "Name": "/test/param", "Labels": [] }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("ValidationException"));
+
+ given()
+ .header("X-Amz-Target", "AmazonSSM.LabelParameterVersion")
+ .contentType(SSM_CONTENT_TYPE)
+ .body("""
+ { "Name": "/test/param", "Labels": [""] }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("ValidationException"));
+
+ given()
+ .header("X-Amz-Target", "AmazonSSM.LabelParameterVersion")
+ .contentType(SSM_CONTENT_TYPE)
+ .body("""
+ { "Name": "/test/param", "Labels": ["%s"] }
+ """.formatted("a".repeat(101)))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("ValidationException"));
+
+ given()
+ .header("X-Amz-Target", "AmazonSSM.LabelParameterVersion")
+ .contentType(SSM_CONTENT_TYPE)
+ .body("""
+ { "Name": "/test/param", "Labels": ["l1","l2","l3","l4","l5","l6","l7","l8","l9","l10","l11"] }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("ValidationException"));
+ }
+
private io.restassured.response.ValidatableResponse describeParameters(String body) {
return given()
.header("X-Amz-Target", "AmazonSSM.DescribeParameters")
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 3875d4daa1..19c2310f2e 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
@@ -201,6 +201,244 @@ class SsmServiceTest {
assertEquals("v3", history.get(2).getValue());
}
+ @Test
+ void getParameterByVersionSelectorReturnsThatVersion() {
+ String region = "eu-west-1";
+ ssmService.putParameter("/app/key", "v1", "SecureString", null, false, region);
+ ssmService.putParameter("/app/key", "v2", "SecureString", null, true, region);
+
+ Parameter first = ssmService.getParameter("/app/key:1", region);
+ assertEquals("/app/key", first.getName());
+ assertEquals("v1", first.getValue());
+ assertEquals(1, first.getVersion());
+ assertEquals(":1", first.getSelector());
+ assertEquals("v2", ssmService.getParameter("/app/key:2", region).getValue());
+ assertEquals("v2", ssmService.getParameter("/app/key", region).getValue());
+ }
+
+ @Test
+ void getParameterByLabelSelectorReturnsLabeledVersion() {
+ String region = "eu-west-1";
+ ssmService.putParameter("/app/key", "v1", "String", null, false, region);
+ ssmService.putParameter("/app/key", "v2", "String", null, true, region);
+ ssmService.labelParameterVersion("/app/key", 1, List.of("previous"), region);
+
+ Parameter labeled = ssmService.getParameter("/app/key:previous", region);
+ assertEquals("v1", labeled.getValue());
+ assertEquals(":previous", labeled.getSelector());
+ }
+
+ @Test
+ void labelParameterVersionRejectsNumericAndReservedLabels() {
+ String region = "eu-west-1";
+ ssmService.putParameter("/app/key", "v1", "String", null, false, region);
+
+ SsmService.LabelParameterVersionResult result = ssmService.labelParameterVersion(
+ "/app/key", 1L, List.of("2", "aws:label", "ssm.label", "valid-label", "valid.label_1"), region);
+
+ assertEquals(1, result.parameterVersion());
+ assertEquals(List.of("2", "aws:label", "ssm.label"), result.invalidLabels());
+
+ Parameter labeled = ssmService.getParameter("/app/key:valid-label", region);
+ assertEquals("v1", labeled.getValue());
+ assertEquals(":valid-label", labeled.getSelector());
+
+ // Numeric label was rejected, so :2 asks for version 2 which does not exist
+ AwsException ex = assertThrows(AwsException.class,
+ () -> ssmService.getParameter("/app/key:2", region));
+ assertEquals("ParameterVersionNotFound", ex.getErrorCode());
+ }
+
+ @Test
+ void labelParameterVersionEmptyLabelsThrowsValidationException() {
+ String region = "eu-west-1";
+ ssmService.putParameter("/app/key", "v1", "String", null, false, region);
+
+ AwsException ex = assertThrows(AwsException.class,
+ () -> ssmService.labelParameterVersion("/app/key", 1L, List.of(), region));
+ assertEquals("ValidationException", ex.getErrorCode());
+ }
+
+ @Test
+ void labelParameterVersionMoreThan10LabelsThrowsValidationException() {
+ String region = "eu-west-1";
+ ssmService.putParameter("/app/key", "v1", "String", null, false, region);
+
+ List<String> elevenLabels = List.of(
+ "l1", "l2", "l3", "l4", "l5", "l6", "l7", "l8", "l9", "l10", "l11");
+ AwsException ex = assertThrows(AwsException.class,
+ () -> ssmService.labelParameterVersion("/app/key", 1L, elevenLabels, region));
+ assertEquals("ValidationException", ex.getErrorCode());
+ }
+
+ @Test
+ void labelParameterVersionEmptyLabelStringThrowsValidationException() {
+ String region = "eu-west-1";
+ ssmService.putParameter("/app/key", "v1", "String", null, false, region);
+
+ AwsException ex = assertThrows(AwsException.class,
+ () -> ssmService.labelParameterVersion("/app/key", 1L, List.of(""), region));
+ assertEquals("ValidationException", ex.getErrorCode());
+ }
+
+ @Test
+ void labelParameterVersionLabelOver100CharsThrowsValidationException() {
+ String region = "eu-west-1";
+ ssmService.putParameter("/app/key", "v1", "String", null, false, region);
+
+ String tooLong = "a".repeat(101);
+ AwsException ex = assertThrows(AwsException.class,
+ () -> ssmService.labelParameterVersion("/app/key", 1L, List.of(tooLong), region));
+ assertEquals("ValidationException", ex.getErrorCode());
+ }
+
+ @Test
+ void labelParameterVersionMovesLabelBetweenVersions() {
+ String region = "eu-west-1";
+ ssmService.putParameter("/app/key", "v1", "String", null, false, region);
+ ssmService.putParameter("/app/key", "v2", "String", null, true, region);
+
+ ssmService.labelParameterVersion("/app/key", 1L, List.of("prod"), region);
+ assertEquals("v1", ssmService.getParameter("/app/key:prod", region).getValue());
+
+ ssmService.labelParameterVersion("/app/key", 2L, List.of("prod"), region);
+ assertEquals("v2", ssmService.getParameter("/app/key:prod", region).getValue());
+ }
+
+ @Test
+ void labelParameterVersionEnforcesMaxLabelsPerVersion() {
+ String region = "eu-west-1";
+ ssmService.putParameter("/app/key", "v1", "String", null, false, region);
+
+ List<String> tenLabels = List.of("l1", "l2", "l3", "l4", "l5", "l6", "l7", "l8", "l9", "l10");
+ SsmService.LabelParameterVersionResult result = ssmService.labelParameterVersion(
+ "/app/key", 1L, tenLabels, region);
+ assertEquals(0, result.invalidLabels().size());
+
+ AwsException ex = assertThrows(AwsException.class,
+ () -> ssmService.labelParameterVersion("/app/key", 1L, List.of("l11"), region));
+ assertEquals("ParameterVersionLabelLimitExceeded", ex.getErrorCode());
+ }
+
+ @Test
+ void labelParameterVersionDefaultsToLatestVersionWhenVersionOmitted() {
+ String region = "eu-west-1";
+ ssmService.putParameter("/app/key", "v1", "String", null, false, region);
+ ssmService.putParameter("/app/key", "v2", "String", null, true, region);
+
+ SsmService.LabelParameterVersionResult result = ssmService.labelParameterVersion(
+ "/app/key", null, List.of("latest-label"), region);
+ assertEquals(2, result.parameterVersion());
+ assertEquals("v2", ssmService.getParameter("/app/key:latest-label", region).getValue());
+ }
+
+ @Test
+ void labelParameterVersionWithExplicitZeroVersionThrowsParameterVersionNotFound() {
+ String region = "eu-west-1";
+ ssmService.putParameter("/app/key", "v1", "String", null, false, region);
+
+ AwsException zero = assertThrows(AwsException.class,
+ () -> ssmService.labelParameterVersion("/app/key", 0L, List.of("prod"), region));
+ assertEquals("ParameterVersionNotFound", zero.getErrorCode());
+
+ AwsException negative = assertThrows(AwsException.class,
+ () -> ssmService.labelParameterVersion("/app/key", -1L, List.of("prod"), region));
+ assertEquals("ParameterVersionNotFound", negative.getErrorCode());
+ }
+
+ @Test
+ void labelParameterVersionDoesNotMutateStoredHistoryObjectsInPlace() {
+ String region = "eu-west-1";
+ ssmService.putParameter("/app/key", "v1", "String", null, false, region);
+ ssmService.putParameter("/app/key", "v2", "String", null, true, region);
+ ssmService.labelParameterVersion("/app/key", 1L, List.of("prod"), region);
+
+ List<ParameterHistory> before = ssmService.getParameterHistory("/app/key", region);
+ ParameterHistory v1Before = before.stream().filter(h -> h.getVersion() == 1).findFirst().orElseThrow();
+ assertTrue(v1Before.getLabels().contains("prod"));
+
+ // Move to version 2
+ ssmService.labelParameterVersion("/app/key", 2L, List.of("prod"), region);
+
+ // Previous history instance should not be mutated in-place
+ assertTrue(v1Before.getLabels().contains("prod"));
+
+ List<ParameterHistory> after = ssmService.getParameterHistory("/app/key", region);
+ ParameterHistory v1After = after.stream().filter(h -> h.getVersion() == 1).findFirst().orElseThrow();
+ ParameterHistory v2After = after.stream().filter(h -> h.getVersion() == 2).findFirst().orElseThrow();
+ assertFalse(v1After.getLabels().contains("prod"));
+ assertTrue(v2After.getLabels().contains("prod"));
+ }
+
+ @Test
+ void concurrentLabelUpdatesDoNotLoseLabels() throws Exception {
+ String region = "eu-west-1";
+ ssmService.putParameter("/app/concurrent", "v1", "String", null, false, region);
+ ssmService.putParameter("/app/concurrent", "v2", "String", null, true, region);
+
+ ExecutorService executor = Executors.newFixedThreadPool(2);
+ CountDownLatch latch = new CountDownLatch(1);
+
+ Future<?> f1 = executor.submit(() -> {
+ try {
+ latch.await();
+ ssmService.labelParameterVersion("/app/concurrent", 1L, List.of("label-v1"), region);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ });
+
+ Future<?> f2 = executor.submit(() -> {
+ try {
+ latch.await();
+ ssmService.labelParameterVersion("/app/concurrent", 2L, List.of("label-v2"), region);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ });
+
+ latch.countDown();
+ f1.get();
+ f2.get();
+ executor.shutdown();
+
+ Parameter p1 = ssmService.getParameter("/app/concurrent:label-v1", region);
+ Parameter p2 = ssmService.getParameter("/app/concurrent:label-v2", region);
+ assertEquals("v1", p1.getValue());
+ assertEquals("v2", p2.getValue());
+ }
+
+ @Test
+ void getParameterWithUnknownVersionThrowsParameterVersionNotFound() {
+ String region = "eu-west-1";
+ ssmService.putParameter("/app/key", "v1", "String", null, false, region);
+
+ AwsException version = assertThrows(AwsException.class,
+ () -> ssmService.getParameter("/app/key:9", region));
+ assertEquals("ParameterVersionNotFound", version.getErrorCode());
+ AwsException label = assertThrows(AwsException.class,
+ () -> ssmService.getParameter("/app/key:nolabel", region));
+ assertEquals("ParameterVersionNotFound", label.getErrorCode());
+ }
+
+ @Test
+ void getParameterWithSelectorOnMissingParameterThrowsParameterNotFound() {
+ AwsException ex = assertThrows(AwsException.class,
+ () -> ssmService.getParameter("/missing:1", "eu-west-1"));
+ assertEquals("ParameterNotFound", ex.getErrorCode());
+ }
+
+ @Test
+ void getParametersSkipsUnknownVersionSelector() {
+ String region = "eu-west-1";
+ ssmService.putParameter("/app/key", "v1", "String", null, false, region);
+ ssmService.putParameter("/app/key", "v2", "String", null, true, region);
+
+ List<Parameter> found = ssmService.getParameters(List.of("/app/key:1", "/app/key:9"), region);
+ assertEquals(1, found.size());
+ assertEquals("v1", found.getFirst().getValue());
+ }
+
@Test
void parameterHistoryIsTrimmedToMax() {
String region = "eu-west-1";