Skip to content

armgit / floci

Public Imported from GitHub
0

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

feat(ssm): support UnlabelParameterVersion (#5339)

Ovidiu (Ovi)4f34a903fcf3
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SsmTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SsmTest.java
index d4e0ae2376..4f3b20332d 100644
--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SsmTest.java
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SsmTest.java
@@ -36,6 +36,8 @@ import software.amazon.awssdk.services.ssm.model.RemoveTagsFromResourceRequest;
import software.amazon.awssdk.services.ssm.model.SendCommandRequest;
import software.amazon.awssdk.services.ssm.model.SendCommandResponse;
import software.amazon.awssdk.services.ssm.model.SsmException;
+import software.amazon.awssdk.services.ssm.model.UnlabelParameterVersionRequest;
+import software.amazon.awssdk.services.ssm.model.UnlabelParameterVersionResponse;
import java.util.List;
import java.util.Map;
@@ -109,6 +111,38 @@ class SsmTest {
// No exception means success
}
+ @Test
+ void unlabelParameterVersion() {
+ String name = "/sdk-test/unlabel";
+ ssm.putParameter(PutParameterRequest.builder()
+ .name(name)
+ .value("v1")
+ .type(ParameterType.STRING)
+ .overwrite(true)
+ .build());
+ try {
+ ssm.labelParameterVersion(LabelParameterVersionRequest.builder()
+ .name(name)
+ .labels("prod", "stable")
+ .parameterVersion(1L)
+ .build());
+
+ UnlabelParameterVersionResponse response = ssm.unlabelParameterVersion(
+ UnlabelParameterVersionRequest.builder()
+ .name(name)
+ .parameterVersion(1L)
+ .labels("prod", "missing")
+ .build());
+
+ assertThat(response.removedLabels()).containsExactly("prod");
+ assertThat(response.invalidLabels()).containsExactly("missing");
+ assertThat(ssm.getParameterHistory(GetParameterHistoryRequest.builder().name(name).build())
+ .parameters().get(0).labels()).containsExactly("stable");
+ } finally {
+ ssm.deleteParameter(DeleteParameterRequest.builder().name(name).build());
+ }
+ }
+
@Test
@Order(4)
void getParameterHistory() {
diff --git a/compatibility-tests/sdk-test-python/tests/test_ssm.py b/compatibility-tests/sdk-test-python/tests/test_ssm.py
index eb2bf4d768..03279426bc 100644
--- a/compatibility-tests/sdk-test-python/tests/test_ssm.py
+++ b/compatibility-tests/sdk-test-python/tests/test_ssm.py
@@ -45,6 +45,26 @@ class TestSSMParameter:
finally:
ssm_client.delete_parameter(Name=param_name)
+ def test_unlabel_parameter_version(self, ssm_client, unique_name):
+ """Test UnlabelParameterVersion removes attached labels and reports the rest."""
+ param_name = f"/pytest-sdk-test/{unique_name}"
+
+ ssm_client.put_parameter(Name=param_name, Value="value", Type="String")
+ try:
+ ssm_client.label_parameter_version(
+ Name=param_name, Labels=["py-prod", "py-stable"], ParameterVersion=1
+ )
+ response = ssm_client.unlabel_parameter_version(
+ Name=param_name, Labels=["py-prod", "py-missing"], ParameterVersion=1
+ )
+ assert response["RemovedLabels"] == ["py-prod"]
+ assert response["InvalidLabels"] == ["py-missing"]
+
+ history = ssm_client.get_parameter_history(Name=param_name)
+ assert history["Parameters"][0]["Labels"] == ["py-stable"]
+ finally:
+ ssm_client.delete_parameter(Name=param_name)
+
def test_get_parameter_history(self, ssm_client, unique_name):
"""Test GetParameterHistory returns parameter versions."""
param_name = f"/pytest-sdk-test/{unique_name}"
diff --git a/docs/services/ssm.md b/docs/services/ssm.md
index 146e1281ad..eab4b49b30 100644
--- a/docs/services/ssm.md
+++ b/docs/services/ssm.md
@@ -18,6 +18,7 @@
| `GetParameterHistory` | List all versions of a parameter |
| `DescribeParameters` | List parameters with optional filters |
| `LabelParameterVersion` | Attach a label to a specific version |
+| `UnlabelParameterVersion` | Remove labels from a specific version |
| `AddTagsToResource` | Tag a parameter |
| `ListTagsForResource` | List tags on a parameter |
| `RemoveTagsFromResource` | Remove tags from a parameter |
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 7e72c6a9b6..c90660fa04 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
@@ -26,6 +26,7 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.Response;
+import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
@@ -65,6 +66,7 @@ public class SsmJsonHandler {
case "GetParameterHistory" -> handleGetParameterHistory(request, region);
case "DescribeParameters" -> handleDescribeParameters(request, region);
case "LabelParameterVersion" -> handleLabelParameterVersion(request, region);
+ case "UnlabelParameterVersion" -> handleUnlabelParameterVersion(request, region);
case "AddTagsToResource" -> handleAddTagsToResource(request, region);
case "ListTagsForResource" -> handleListTagsForResource(request, region);
case "RemoveTagsFromResource" -> handleRemoveTagsFromResource(request, region);
@@ -1021,46 +1023,70 @@ public class SsmJsonHandler {
return Response.ok(response).build();
}
- private static final int MAX_LABELS = 10;
- private static final int MAX_LABEL_LENGTH = 100;
+ private static final BigDecimal LONG_MIN = BigDecimal.valueOf(Long.MIN_VALUE);
+ private static final BigDecimal LONG_MAX = BigDecimal.valueOf(Long.MAX_VALUE);
private List<String> requireLabels(JsonNode request) {
+ List<String> labels = optionalLabels(request);
+ String violation = SsmService.labelListViolation(labels);
+ if (violation != null) {
+ throw SsmService.validationErrors(List.of(violation));
+ }
+ return labels;
+ }
+
+ /** The {@code Labels} member, or null when absent; a non-string member fails to deserialize, as on AWS. */
+ private static List<String> optionalLabels(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);
+ return null;
}
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);
+ if (l.isNull()) {
+ labels.add(null);
+ } else if (l.isTextual()) {
+ labels.add(l.textValue());
+ } else {
+ throw serializationException(l, "String");
}
- labels.add(label);
}
return labels;
}
+ private static String optionalString(JsonNode request, String field) {
+ JsonNode node = request.path(field);
+ if (node.isMissingNode() || node.isNull()) {
+ return null;
+ }
+ if (!node.isTextual()) {
+ throw serializationException(node, "String");
+ }
+ return node.textValue();
+ }
+
+ /** AWS truncates a fractional number and clamps one outside the range of a long. */
+ private static Long optionalLong(JsonNode request, String field) {
+ JsonNode node = request.path(field);
+ if (node.isMissingNode() || node.isNull()) {
+ return null;
+ }
+ if (!node.isNumber()) {
+ throw serializationException(node, "Long");
+ }
+ return node.decimalValue().max(LONG_MIN).min(LONG_MAX).longValue();
+ }
+
+ private static AwsException serializationException(JsonNode node, String targetType) {
+ String token = switch (node.getNodeType()) {
+ case STRING -> "STRING_VALUE";
+ case NUMBER -> "NUMBER_VALUE";
+ case BOOLEAN -> node.booleanValue() ? "TRUE_VALUE" : "FALSE_VALUE";
+ default -> node.getNodeType().name();
+ };
+ return new AwsException("SerializationException", token + " can not be converted to a " + targetType, 400);
+ }
+
private Response handleLabelParameterVersion(JsonNode request, String region) {
String name = request.path("Name").asText();
Long parameterVersion = request.hasNonNull("ParameterVersion")
@@ -1079,6 +1105,41 @@ public class SsmJsonHandler {
return Response.ok(response).build();
}
+ private Response handleUnlabelParameterVersion(JsonNode request, String region) {
+ String name = optionalString(request, "Name");
+ Long parameterVersion = optionalLong(request, "ParameterVersion");
+ List<String> labels = optionalLabels(request);
+
+ List<String> violations = new ArrayList<>();
+ if (name == null) {
+ violations.add("Value null at 'name' failed to satisfy constraint: Member must not be null");
+ } else if (name.isEmpty()) {
+ violations.add("Value '' at 'name' failed to satisfy constraint: Member must have length greater than or equal to 1");
+ }
+ if (parameterVersion == null) {
+ violations.add("Value null at 'parameterVersion' failed to satisfy constraint: Member must not be null");
+ }
+ String labelViolation = SsmService.labelListViolation(labels);
+ if (labelViolation != null) {
+ violations.add(labelViolation);
+ }
+ if (!violations.isEmpty()) {
+ throw SsmService.validationErrors(violations);
+ }
+
+ SsmService.UnlabelParameterVersionResult result = ssmService.unlabelParameterVersion(
+ name, parameterVersion, labels, region);
+
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode removedArray = objectMapper.createArrayNode();
+ result.removedLabels().forEach(removedArray::add);
+ response.set("RemovedLabels", removedArray);
+ ArrayNode invalidArray = objectMapper.createArrayNode();
+ result.invalidLabels().forEach(invalidArray::add);
+ response.set("InvalidLabels", invalidArray);
+ return Response.ok(response).build();
+ }
+
private Response handleAddTagsToResource(JsonNode request, String region) {
String resourceId = request.path("ResourceId").asText();
Map<String, String> tags = new LinkedHashMap<>();
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 e6efa2a46d..b39eb2d31a 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
@@ -62,6 +62,12 @@ public class SsmService implements ResourceProvider {
private static final String TAG_KEY_REGEX = "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)$";
private static final Pattern TAG_KEY_PATTERN = Pattern.compile(TAG_KEY_REGEX);
private static final int MAX_TAG_KEY_LENGTH = 128;
+ /** The tail AWS appends to every rejected parameter name, whichever prefix the operation reserves. */
+ private static final String PARAMETER_NAME_FORMAT_RULE = "If formed as a path, it can consist of sub-paths "
+ + "divided by slash symbol; each sub-path can be formed as a mix of letters, numbers and the following "
+ + "3 symbols .-_";
+ /** A bare name, or a path of non-empty segments; AWS also lets a colon through here. */
+ private static final Pattern UNLABEL_NAME_PATTERN = Pattern.compile("[A-Za-z0-9_.:-]+|(/[A-Za-z0-9_.:-]+)+");
/**
* Account-default values for the service settings floci models. AWS rejects
@@ -454,9 +460,7 @@ public class SsmService implements ResourceProvider {
|| lower.startsWith("aws/") || lower.startsWith("ssm/")) {
throw new AwsException("ValidationException",
"Parameter name: can't be prefixed with \"aws\" or \"ssm\" (case-insensitive). "
- + "If formed as a path, it can consist of sub-paths divided by slash symbol; "
- + "each sub-path can be formed as a mix of letters, numbers and the following "
- + "3 symbols .-_", 400);
+ + PARAMETER_NAME_FORMAT_RULE, 400);
}
}
@@ -560,7 +564,7 @@ public class SsmService implements ResourceProvider {
return !paramName.substring(normalizedPath.length()).contains("/");
}
- public void deleteParameter(String name, String region) {
+ public synchronized void deleteParameter(String name, String region) {
String storageKey = regionKey(region, name);
if (parameterStore.get(storageKey).isEmpty()) {
throw new AwsException("ParameterNotFound",
@@ -571,7 +575,7 @@ public class SsmService implements ResourceProvider {
LOG.infov("Deleted parameter: {0}", name);
}
- public List<String> deleteParameters(List<String> names, String region) {
+ public synchronized List<String> deleteParameters(List<String> names, String region) {
List<String> deleted = new ArrayList<>();
for (String name : names) {
String storageKey = regionKey(region, name);
@@ -686,28 +690,7 @@ public class SsmService implements ResourceProvider {
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);
- }
- }
+ validateLabelList(labels);
String storageKey = regionKey(region, name);
Parameter current = parameterStore.get(storageKey).orElseThrow(() ->
@@ -791,6 +774,109 @@ public class SsmService implements ResourceProvider {
return labelParameterVersion(name, Long.valueOf(parameterVersion), labels, region);
}
+ public record UnlabelParameterVersionResult(List<String> removedLabels, List<String> invalidLabels) {}
+
+ /**
+ * Detaches labels from one version. A label that is not on that version, including one
+ * attached to a different version, is reported in {@code invalidLabels} and left in place.
+ * As on AWS, {@code removedLabels} follows the order the labels are stored on the version,
+ * {@code invalidLabels} the order of the request, and error messages echo the name as sent
+ * although the lookup ignores surrounding whitespace.
+ */
+ public synchronized UnlabelParameterVersionResult unlabelParameterVersion(String name, long parameterVersion,
+ List<String> labels, String region) {
+ validateLabelList(labels);
+ String trimmed = name.strip();
+ if (AwsArnUtils.isArn(trimmed)) {
+ throw new AwsException("ValidationException", "Parameter ARN is not supported for this operation.", 400);
+ }
+ String bare = trimmed.startsWith("/") ? trimmed.substring(1) : trimmed;
+ String lower = bare.toLowerCase(Locale.ROOT);
+ if (!UNLABEL_NAME_PATTERN.matcher(trimmed).matches() || lower.startsWith("ssm")) {
+ throw new AwsException("ValidationException",
+ "Parameter name: can't be prefixed with \"ssm\" (case-insensitive). "
+ + PARAMETER_NAME_FORMAT_RULE, 400);
+ }
+ if (lower.startsWith("aws")) { // partition-literal: reserved parameter name prefix
+ throw new AwsException("AccessDeniedException",
+ "No access to reserved parameter name: " + bare + ".", 400);
+ }
+
+ String storageKey = regionKey(region, trimmed);
+ if (parameterStore.get(storageKey).isEmpty()) {
+ throw new AwsException("ParameterNotFound", "Parameter " + name + " not found.", 400);
+ }
+
+ List<ParameterHistory> existingHistory = historyStore.get(storageKey).orElse(List.of());
+ List<ParameterHistory> updatedHistory = new ArrayList<>(existingHistory.size());
+ ParameterHistory targetCopy = null;
+ for (ParameterHistory h : existingHistory) {
+ ParameterHistory copy = new ParameterHistory(h);
+ if (copy.getVersion() == parameterVersion) {
+ targetCopy = copy;
+ }
+ updatedHistory.add(copy);
+ }
+ if (targetCopy == null) {
+ throw new AwsException("ParameterVersionNotFound",
+ "Systems Manager could not find version " + parameterVersion + " of " + name
+ + ". Verify the version and try again.", 400);
+ }
+
+ List<String> targetLabels = targetCopy.getLabels() != null
+ ? new ArrayList<>(targetCopy.getLabels())
+ : new ArrayList<>();
+ Set<String> requested = new LinkedHashSet<>(labels);
+ List<String> removedLabels = targetLabels.stream().filter(requested::contains).toList();
+ List<String> invalidLabels = requested.stream().filter(l -> !targetLabels.contains(l)).toList();
+
+ if (!removedLabels.isEmpty()) {
+ targetLabels.removeAll(requested);
+ targetCopy.setLabels(targetLabels);
+ historyStore.put(storageKey, updatedHistory);
+ LOG.infov("Removed labels {0} from parameter {1} version {2}", removedLabels, trimmed, parameterVersion);
+ }
+ return new UnlabelParameterVersionResult(removedLabels, invalidLabels);
+ }
+
+ private static void validateLabelList(List<String> labels) {
+ String violation = labelListViolation(labels);
+ if (violation != null) {
+ throw validationErrors(List.of(violation));
+ }
+ }
+
+ /**
+ * The constraint a {@code ParameterLabelList} breaks, worded as AWS words it, or null. AWS
+ * renders the list with Java's {@code List.toString}, so {@code [""]} reads {@code '[]'}.
+ */
+ static String labelListViolation(List<String> labels) {
+ if (labels == null) {
+ return "Value null at 'labels' failed to satisfy constraint: Member must not be null";
+ }
+ String prefix = "Value '" + labels + "' at 'labels' failed to satisfy constraint: ";
+ if (labels.isEmpty()) {
+ return prefix + "Member must have length greater than or equal to 1";
+ }
+ if (labels.size() > 10) {
+ return prefix + "Member must have length less than or equal to 10";
+ }
+ boolean memberOutOfRange = labels.stream()
+ .anyMatch(label -> label == null || label.isEmpty() || label.length() > 100);
+ if (memberOutOfRange) {
+ return prefix + "Member must satisfy constraint: [Member must have length less than or equal to 100, "
+ + "Member must have length greater than or equal to 1]";
+ }
+ return null;
+ }
+
+ static AwsException validationErrors(List<String> violations) {
+ String count = violations.size() == 1
+ ? "1 validation error detected: "
+ : violations.size() + " validation errors detected: ";
+ return new AwsException("ValidationException", count + String.join("; ", violations), 400);
+ }
+
private static boolean isValidLabel(String label) {
if (label == null || label.isEmpty() || label.length() > 100) {
return false;
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 187924b1aa..9152af7380 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
@@ -1988,53 +1988,217 @@ class SsmIntegrationTest {
@Test
void labelParameterVersion_validationErrors() {
+ String prefix = "1 validation error detected: ";
+ String memberRange = "Member must satisfy constraint: [Member must have length less than or equal to 100, "
+ + "Member must have length greater than or equal to 1]";
+ labelParameterVersion("""
+ { "Name": "/test/param", "Labels": [] }
+ """)
+ .statusCode(400)
+ .body("__type", equalTo("ValidationException"))
+ .body("message", equalTo(prefix + "Value '[]' at 'labels' failed to satisfy constraint: "
+ + "Member must have length greater than or equal to 1"));
+
+ labelParameterVersion("""
+ { "Name": "/test/param", "Labels": [""] }
+ """)
+ .statusCode(400)
+ .body("__type", equalTo("ValidationException"))
+ .body("message", equalTo(prefix + "Value '[]' at 'labels' failed to satisfy constraint: " + memberRange));
+
+ String tooLong = "a".repeat(101);
+ labelParameterVersion("""
+ { "Name": "/test/param", "Labels": ["%s"] }
+ """.formatted(tooLong))
+ .statusCode(400)
+ .body("__type", equalTo("ValidationException"))
+ .body("message", equalTo(prefix + "Value '[" + tooLong + "]' at 'labels' failed to satisfy constraint: "
+ + memberRange));
+
+ labelParameterVersion("""
+ { "Name": "/test/param", "Labels": ["l1","l2","l3","l4","l5","l6","l7","l8","l9","l10","l11"] }
+ """)
+ .statusCode(400)
+ .body("__type", equalTo("ValidationException"))
+ .body("message", equalTo(prefix + "Value '[l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, l11]' at 'labels' "
+ + "failed to satisfy constraint: Member must have length less than or equal to 10"));
+
+ labelParameterVersion("""
+ { "Name": "/test/param", "Labels": [5] }
+ """)
+ .statusCode(400)
+ .body("__type", equalTo("SerializationException"))
+ .body("message", equalTo("NUMBER_VALUE can not be converted to a String"));
+ }
+
+ private io.restassured.response.ValidatableResponse labelParameterVersion(String body) {
+ return given()
+ .header("X-Amz-Target", "AmazonSSM.LabelParameterVersion")
+ .contentType(SSM_CONTENT_TYPE)
+ .body(body)
+ .when()
+ .post("/")
+ .then();
+ }
+
+ @Test
+ void unlabelParameterVersionRemovesLabels() {
+ given()
+ .header("X-Amz-Target", "AmazonSSM.PutParameter")
+ .contentType(SSM_CONTENT_TYPE)
+ .body("""
+ { "Name": "/unlabel/param", "Value": "v1", "Type": "String" }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
given()
.header("X-Amz-Target", "AmazonSSM.LabelParameterVersion")
.contentType(SSM_CONTENT_TYPE)
.body("""
- { "Name": "/test/param", "Labels": [] }
+ { "Name": "/unlabel/param", "ParameterVersion": 1, "Labels": ["prod", "stable"] }
""")
.when()
.post("/")
.then()
- .statusCode(400)
- .body("__type", equalTo("ValidationException"));
+ .statusCode(200);
given()
- .header("X-Amz-Target", "AmazonSSM.LabelParameterVersion")
+ .header("X-Amz-Target", "AmazonSSM.UnlabelParameterVersion")
.contentType(SSM_CONTENT_TYPE)
.body("""
- { "Name": "/test/param", "Labels": [""] }
+ { "Name": "/unlabel/param", "ParameterVersion": 1, "Labels": ["prod", "missing"] }
""")
.when()
.post("/")
.then()
- .statusCode(400)
- .body("__type", equalTo("ValidationException"));
+ .statusCode(200)
+ .body("RemovedLabels", contains("prod"))
+ .body("InvalidLabels", contains("missing"));
given()
- .header("X-Amz-Target", "AmazonSSM.LabelParameterVersion")
+ .header("X-Amz-Target", "AmazonSSM.GetParameter")
.contentType(SSM_CONTENT_TYPE)
.body("""
- { "Name": "/test/param", "Labels": ["%s"] }
- """.formatted("a".repeat(101)))
+ { "Name": "/unlabel/param:prod" }
+ """)
.when()
.post("/")
.then()
.statusCode(400)
- .body("__type", equalTo("ValidationException"));
+ .body("__type", equalTo("ParameterVersionNotFound"));
+
+ given()
+ .header("X-Amz-Target", "AmazonSSM.GetParameterHistory")
+ .contentType(SSM_CONTENT_TYPE)
+ .body("""
+ { "Name": "/unlabel/param" }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("Parameters[0].Labels", contains("stable"));
+ }
+ @Test
+ void unlabelParameterVersion_errors() {
+ given()
+ .header("X-Amz-Target", "AmazonSSM.PutParameter")
+ .contentType(SSM_CONTENT_TYPE)
+ .body("""
+ { "Name": "/unlabel/errors", "Value": "v1", "Type": "String" }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
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"] }
+ { "Name": "/unlabel/errors", "ParameterVersion": 1, "Labels": ["prod"] }
""")
.when()
.post("/")
.then()
+ .statusCode(200);
+
+ unlabel("{}")
.statusCode(400)
- .body("__type", equalTo("ValidationException"));
+ .body("__type", equalTo("ValidationException"))
+ .body("message", equalTo("3 validation errors detected: "
+ + "Value null at 'name' failed to satisfy constraint: Member must not be null; "
+ + "Value null at 'parameterVersion' failed to satisfy constraint: Member must not be null; "
+ + "Value null at 'labels' failed to satisfy constraint: Member must not be null"));
+ unlabel("""
+ { "Name": "", "ParameterVersion": 1, "Labels": [] }
+ """)
+ .statusCode(400)
+ .body("message", equalTo("2 validation errors detected: "
+ + "Value '' at 'name' failed to satisfy constraint: Member must have length greater than or equal to 1; "
+ + "Value '[]' at 'labels' failed to satisfy constraint: Member must have length greater than or equal to 1"));
+ unlabel("""
+ { "Name": "/unlabel/errors", "ParameterVersion": "1", "Labels": ["prod"] }
+ """)
+ .statusCode(400)
+ .body("__type", equalTo("SerializationException"))
+ .body("message", equalTo("STRING_VALUE can not be converted to a Long"));
+ unlabel("""
+ { "Name": "/unlabel/errors", "ParameterVersion": 1, "Labels": [5] }
+ """)
+ .statusCode(400)
+ .body("__type", equalTo("SerializationException"))
+ .body("message", equalTo("NUMBER_VALUE can not be converted to a String"));
+ unlabel("""
+ { "Name": "arn:aws:ssm:us-east-1:000000000000:parameter/unlabel/errors", "ParameterVersion": 1, "Labels": ["prod"] }
+ """)
+ .statusCode(400)
+ .body("__type", equalTo("ValidationException"))
+ .body("message", equalTo("Parameter ARN is not supported for this operation."));
+ unlabel("""
+ { "Name": "/unlabel/errors", "ParameterVersion": 5, "Labels": ["prod"] }
+ """)
+ .statusCode(400)
+ .body("__type", equalTo("ParameterVersionNotFound"))
+ .body("message", equalTo("Systems Manager could not find version 5 of /unlabel/errors. "
+ + "Verify the version and try again."));
+ unlabel("""
+ { "Name": "/unlabel/no-such-param", "ParameterVersion": 1, "Labels": ["prod"] }
+ """)
+ .statusCode(400)
+ .body("__type", equalTo("ParameterNotFound"))
+ .body("message", equalTo("Parameter /unlabel/no-such-param not found."));
+
+ given()
+ .header("X-Amz-Target", "AmazonSSM.GetParameterHistory")
+ .contentType(SSM_CONTENT_TYPE)
+ .body("""
+ { "Name": "/unlabel/errors" }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("Parameters[0].Labels", contains("prod"));
+
+ // AWS truncates a fractional version rather than rejecting it.
+ unlabel("""
+ { "Name": "/unlabel/errors", "ParameterVersion": 1.9, "Labels": ["prod"] }
+ """)
+ .statusCode(200)
+ .body("RemovedLabels", contains("prod"));
+ }
+
+ private io.restassured.response.ValidatableResponse unlabel(String body) {
+ return given()
+ .header("X-Amz-Target", "AmazonSSM.UnlabelParameterVersion")
+ .contentType(SSM_CONTENT_TYPE)
+ .body(body)
+ .when()
+ .post("/")
+ .then();
}
private io.restassured.response.ValidatableResponse describeParameters(String body) {
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 6ce57d4f24..a3050d20ac 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
@@ -499,6 +499,210 @@ class SsmServiceTest {
assertEquals("v2", p2.getValue());
}
+ @Test
+ void unlabelParameterVersionRemovesLabelsAndReportsMissingOnes() {
+ String region = "eu-west-1";
+ ssmService.putParameter("/app/key", "v1", "String", null, false, region);
+ ssmService.labelParameterVersion("/app/key", 1L, List.of("prod", "stable"), region);
+
+ SsmService.UnlabelParameterVersionResult result = ssmService.unlabelParameterVersion(
+ "/app/key", 1L, List.of("prod", "never-attached", "prod"), region);
+
+ assertEquals(List.of("prod"), result.removedLabels());
+ assertEquals(List.of("never-attached"), result.invalidLabels());
+ ParameterHistory v1 = ssmService.getParameterHistory("/app/key", region).get(0);
+ assertEquals(List.of("stable"), v1.getLabels());
+ AwsException ex = assertThrows(AwsException.class,
+ () -> ssmService.getParameter("/app/key:prod", region));
+ assertEquals("ParameterVersionNotFound", ex.getErrorCode());
+ assertEquals("v1", ssmService.getParameter("/app/key:stable", region).getValue());
+ }
+
+ @Test
+ void unlabelParameterVersionLeavesLabelOnAnotherVersionInPlace() {
+ 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", 2L, List.of("prod"), region);
+
+ SsmService.UnlabelParameterVersionResult result = ssmService.unlabelParameterVersion(
+ "/app/key", 1L, List.of("prod"), region);
+
+ assertEquals(List.of(), result.removedLabels());
+ assertEquals(List.of("prod"), result.invalidLabels());
+ assertEquals("v2", ssmService.getParameter("/app/key:prod", region).getValue());
+ }
+
+ @Test
+ void unlabelParameterVersionMissingParameterThrowsParameterNotFound() {
+ AwsException ex = assertThrows(AwsException.class,
+ () -> ssmService.unlabelParameterVersion("/app/missing", 1L, List.of("prod"), "eu-west-1"));
+ assertEquals("ParameterNotFound", ex.getErrorCode());
+ }
+
+ @Test
+ void unlabelParameterVersionUnknownVersionThrowsParameterVersionNotFound() {
+ String region = "eu-west-1";
+ ssmService.putParameter("/app/key", "v1", "String", null, false, region);
+
+ AwsException unknown = assertThrows(AwsException.class,
+ () -> ssmService.unlabelParameterVersion("/app/key", 2L, List.of("prod"), region));
+ assertEquals("ParameterVersionNotFound", unknown.getErrorCode());
+ assertEquals("Systems Manager could not find version 2 of /app/key. Verify the version and try again.",
+ unknown.getMessage());
+ AwsException zero = assertThrows(AwsException.class,
+ () -> ssmService.unlabelParameterVersion("/app/key", 0L, List.of("prod"), region));
+ assertEquals("ParameterVersionNotFound", zero.getErrorCode());
+ }
+
+ @Test
+ void unlabelParameterVersionRejectsEmptyOrOversizedLabelLists() {
+ String region = "eu-west-1";
+ ssmService.putParameter("/app/key", "v1", "String", null, false, region);
+
+ AwsException empty = assertThrows(AwsException.class,
+ () -> ssmService.unlabelParameterVersion("/app/key", 1L, List.of(), region));
+ assertEquals("ValidationException", empty.getErrorCode());
+ List<String> elevenLabels = List.of(
+ "l1", "l2", "l3", "l4", "l5", "l6", "l7", "l8", "l9", "l10", "l11");
+ AwsException tooMany = assertThrows(AwsException.class,
+ () -> ssmService.unlabelParameterVersion("/app/key", 1L, elevenLabels, region));
+ assertEquals("ValidationException", tooMany.getErrorCode());
+ }
+
+ @Test
+ void deletesWaitForTheMonitorThatLabelUpdatesHold() throws Exception {
+ String region = "eu-west-1";
+ ssmService.putParameter("/app/one", "v1", "String", null, false, region);
+ ssmService.putParameter("/app/two", "v1", "String", null, false, region);
+ List<Thread> deleters = List.of(
+ new Thread(() -> ssmService.deleteParameter("/app/one", region)),
+ new Thread(() -> ssmService.deleteParameters(List.of("/app/two"), region)));
+
+ // Holding the monitor stands in for a label or unlabel call between its lookup and its history write.
+ synchronized (ssmService) {
+ for (Thread deleter : deleters) {
+ deleter.start();
+ long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
+ while (deleter.getState() != Thread.State.BLOCKED) {
+ assertTrue(System.nanoTime() < deadline, "delete did not wait for the service monitor");
+ Thread.onSpinWait();
+ }
+ }
+ assertEquals("v1", ssmService.getParameter("/app/one", region).getValue());
+ assertEquals("v1", ssmService.getParameter("/app/two", region).getValue());
+ }
+ for (Thread deleter : deleters) {
+ deleter.join(TimeUnit.SECONDS.toMillis(5));
+ }
+
+ assertThrows(AwsException.class, () -> ssmService.getParameter("/app/one", region));
+ assertThrows(AwsException.class, () -> ssmService.getParameter("/app/two", region));
+ }
+
+ @Test
+ void unlabelParameterVersionReturnsRemovedLabelsInStoredOrder() {
+ String region = "eu-west-1";
+ ssmService.putParameter("/app/key", "v1", "String", null, false, region);
+ ssmService.labelParameterVersion("/app/key", 1L, List.of("mike", "zulu", "alpha"), region);
+
+ SsmService.UnlabelParameterVersionResult result = ssmService.unlabelParameterVersion(
+ "/app/key", 1L, List.of("alpha", "yankee", "mike", "charlie"), region);
+
+ assertEquals(List.of("mike", "alpha"), result.removedLabels());
+ assertEquals(List.of("yankee", "charlie"), result.invalidLabels());
+ }
+
+ @Test
+ void unlabelParameterVersionIgnoresSurroundingWhitespaceButEchoesTheNameAsSent() {
+ String region = "eu-west-1";
+ ssmService.putParameter("/app/key", "v1", "String", null, false, region);
+ ssmService.labelParameterVersion("/app/key", 1L, List.of("prod"), region);
+
+ SsmService.UnlabelParameterVersionResult result = ssmService.unlabelParameterVersion(
+ " \t/app/key ", 1L, List.of("prod"), region);
+ assertEquals(List.of("prod"), result.removedLabels());
+
+ AwsException missing = assertThrows(AwsException.class,
+ () -> ssmService.unlabelParameterVersion(" /app/nope ", 1L, List.of("prod"), region));
+ assertEquals("Parameter /app/nope not found.", missing.getMessage());
+ AwsException version = assertThrows(AwsException.class,
+ () -> ssmService.unlabelParameterVersion(" /app/key ", 9L, List.of("prod"), region));
+ assertEquals("Systems Manager could not find version 9 of /app/key . Verify the version and try again.",
+ version.getMessage());
+ }
+
+ @Test
+ void unlabelParameterVersionRejectsAnArnBeforeLookingItUp() {
+ AwsException ex = assertThrows(AwsException.class,
+ () -> ssmService.unlabelParameterVersion("arn:aws:ssm:us-east-1:123456789012:parameter/nope",
+ 9L, List.of("prod"), "us-east-1"));
+ assertEquals("ValidationException", ex.getErrorCode());
+ assertEquals("Parameter ARN is not supported for this operation.", ex.getMessage());
+ }
+
+ @Test
+ void unlabelParameterVersionRejectsMalformedAndSsmPrefixedNames() {
+ String expected = "Parameter name: can't be prefixed with \"ssm\" (case-insensitive). If formed as a path, "
+ + "it can consist of sub-paths divided by slash symbol; each sub-path can be formed as a mix of "
+ + "letters, numbers and the following 3 symbols .-_";
+ for (String name : List.of("ssm-foo", "/ssm", "/SSM/x", "/a#b", "/a//b", "/a/b/", "a/b", "/a b", " ",
+ "/aws/a#b")) {
+ AwsException ex = assertThrows(AwsException.class,
+ () -> ssmService.unlabelParameterVersion(name, 1L, List.of("prod"), "us-east-1"), name);
+ assertEquals("ValidationException", ex.getErrorCode(), name);
+ assertEquals(expected, ex.getMessage(), name);
+ }
+ for (String name : List.of("/a:b/c", "plain-name", "/x/ssm-y", "/x/aws")) {
+ AwsException ex = assertThrows(AwsException.class,
+ () -> ssmService.unlabelParameterVersion(name, 1L, List.of("prod"), "us-east-1"), name);
+ assertEquals("ParameterNotFound", ex.getErrorCode(), name);
+ }
+ }
+
+ @Test
+ void unlabelParameterVersionDeniesReservedAwsNames() {
+ AwsException path = assertThrows(AwsException.class,
+ () -> ssmService.unlabelParameterVersion("/AWS/foo", 1L, List.of("prod"), "us-east-1"));
+ assertEquals("AccessDeniedException", path.getErrorCode());
+ assertEquals("No access to reserved parameter name: AWS/foo.", path.getMessage());
+ AwsException bare = assertThrows(AwsException.class,
+ () -> ssmService.unlabelParameterVersion("awsfoo", 1L, List.of("prod"), "us-east-1"));
+ assertEquals("No access to reserved parameter name: awsfoo.", bare.getMessage());
+ }
+
+ @Test
+ void labelListViolationWordsEachConstraintAsAws() {
+ String prefix = "failed to satisfy constraint: ";
+ String member = "Member must satisfy constraint: [Member must have length less than or equal to 100, "
+ + "Member must have length greater than or equal to 1]";
+ assertEquals("Value null at 'labels' " + prefix + "Member must not be null",
+ SsmService.labelListViolation(null));
+ assertEquals("Value '[]' at 'labels' " + prefix + "Member must have length greater than or equal to 1",
+ SsmService.labelListViolation(List.of()));
+ assertEquals("Value '[l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, l11]' at 'labels' " + prefix
+ + "Member must have length less than or equal to 10",
+ SsmService.labelListViolation(List.of("l1", "l2", "l3", "l4", "l5", "l6", "l7", "l8", "l9", "l10", "l11")));
+ assertEquals("Value '[]' at 'labels' " + prefix + member, SsmService.labelListViolation(List.of("")));
+ assertEquals("Value '[prod, ]' at 'labels' " + prefix + member,
+ SsmService.labelListViolation(List.of("prod", "")));
+ assertNull(SsmService.labelListViolation(List.of("prod")));
+ }
+
+ @Test
+ void unlabelParameterVersionDoesNotMutateStoredHistoryObjectsInPlace() {
+ String region = "eu-west-1";
+ ssmService.putParameter("/app/key", "v1", "String", null, false, region);
+ ssmService.labelParameterVersion("/app/key", 1L, List.of("prod"), region);
+ ParameterHistory before = ssmService.getParameterHistory("/app/key", region).get(0);
+
+ ssmService.unlabelParameterVersion("/app/key", 1L, List.of("prod"), region);
+
+ assertTrue(before.getLabels().contains("prod"));
+ ParameterHistory after = ssmService.getParameterHistory("/app/key", region).get(0);
+ assertFalse(after.getLabels().contains("prod"));
+ }
+
@Test
void getParameterWithUnknownVersionThrowsParameterVersionNotFound() {
String region = "eu-west-1";